PDA

View Full Version : [SOLVED:] Use Inputbox to Add Column in Excel Table with Multiple Criteria



rorobear
09-02-2021, 08:34 AM
Hello Everyone,
Was wondering if I could get a little VBA help with Table project. I have the code below that works just fine, but I’d like to modify it a little bit.
1. I’d like the code to be specific to the tables in the workbook, (meaning I don’t want to add columns outside of the table)
2. I only want one column at time and 1 Inputbox that will prompt the user to add the column to the left or right of the active cell.
I tried various combinations using listColumns(iCol) or listColumns.ActiveCell etc. none of which work, so I’m reaching out for a little help. The workbook is included. Thank you as always for any assistance.

Private Sub CommandButton1_Click()
Dim iCol As Long
Dim iCount As Long
Dim i As Long

'to get the number of columns that you want to insert with an input box
iCount = InputBox(Prompt:="How many column you want to add?")

'to get the column number where you want to insert the new column
iCol = InputBox(Prompt:= _
"After which column you want to add new column? (Column number)")

'loop to insert new column(s)
For i = 1 To iCount
Columns(iCol).EntireColumn.Insert
Next i
End Sub

p45cal
09-02-2021, 05:22 PM
Look at Sheet2 in the attached.
Click the button to bring up a user form
If a cell within a table is not already selected, select one
Toggle the top button Left/Right
Click Add Column.
Repeat as required
No need to dismiss the userform between operations.

rorobear
09-02-2021, 05:56 PM
p45cal,

This is awesome!!! exactly what I had in mind and I can code it right into my ultimate project. Much thanks for the help and support.

rb

p45cal
09-03-2021, 03:23 AM
It was silly my putting a loop in to find the index column of the active cell; the whole click event code can be reduced to:
Private Sub CommandButton1_Click()
Set myLo = ActiveCell.ListObject
If Not myLo Is Nothing Then
myLo.ListColumns.Add Position:=ActiveCell.Column - myLo.Range.Column + IIf(ToggleButton1, 1, 2)
Else
MsgBox "active cell not in a table"
End If
End Sub

rorobear
09-03-2021, 06:43 AM
Both codes work beautifully, but I do appreciate you going back and reevaluating it. and I do appreciate a simpler code.