Hi everyone,
I have a table in a locked sheet with a certain number of columns by default. Given that the sheet is locked, the user can't add or remove columns so I'm looking for a way to do something like that in VBA:
When the user clicks on the "Add a column" button, a pop-up window appears, asking for the column name. Once entered by the user, a new column is created (with the name entered by the user as its header) and added to the table (on the right side).
Inversely, a user can click on the "Remove a column" button, which requires to provide the name of the column to be removed. Once entered (and if the column does exist), then the column is deleted.
One particular thing is that the remove button can only remove the columns that were added by the user previously (not the default columns that I created initially).
Here's what I have for now but I don't know if I'm making any mistakes here or if there is a cleaner way to write it:
Add a column:
TO remove the column:![]()
Sub AddAColumn() Dim myValue As Variant Dim Table As ListObject Set Table = Sheet1.ListObjects("Table1") showInputBox: myValue = Application.InputBox("Please enter your column name (make sure this name does not already exist)", "Add a Column") If myValue = False Then Exit Sub ElseIf myValue = "" Then MsgBox "You must enter a valid name to add a column.", 48, "You clicked Ok but entered nothing." GoTo showInputBox Else Table.ListColumns.Add (4) Table.HeaderRowRange(4) = myValue End If End Sub
This code does not cover the situation where the user tries to delete one of the default columns (that I dont want him to remove) or if he tries to delete a column that does not exist.![]()
Sub RemoveAColumn() Dim myValue As Variant Dim Table As ListObject Set Table = Sheet1.ListObjects("Table1") showInputBox: myValue = Application.InputBox("Please enter the name of the column you wish to remove", "Remove a Column") If myValue = False Then Exit Sub ElseIf myValue = "" Then MsgBox "You must enter a valid name to remove a column.", 48, "You clicked Ok but entered nothing." GoTo showInputBox Else Table.ListColumns(myValue).Delete End If End Sub
I feel like only VBA can help with that routine but let me know if you think about an alternative!
Thanks a lot
Bookmarks