I have a spreadsheet of data that has the best part of 120 columns of data in it of which I don't all of them, so for file size I delete the ones I do not need. I figured this could be automated and have put together a VB function based on a script I found online which checks column headings against a list of values and if that value is in the list, it deletes the column.
As the column count in the spreadsheet changes due to updates, rather than fix the column reference in the code, I input a start and end column into two cells which the VB code reads but for some reason, I get an error when I select the exact column count. If I choose a smaller column count (ie: table is columns D:K and I choose D:F) the code runs fine and the columns are deleted. Can anyone maybe explain where the code is falling over as I am a newbie to VB.
Many thanks.
Here is the code I'm using and if I can figure out how to upload the example file I will do that as well:
Sub DeleteSpecifcColumn()
Dim rngFound As Range, rngToDelete As Range
Dim strFirstAddress, fstCol, LstCol As String
Dim varList As Variant
Dim lngCounter As Long
fstCol = ActiveSheet.Range("B2").Value
LstCol = ActiveSheet.Range("B3").Value
Application.ScreenUpdating = False
'varList = Range("Sheet1!B3:B8").Value
varList = ActiveSheet.ListObjects("Delete").ListColumns(1).DataBodyRange
For lngCounter = LBound(varList) To UBound(varList)
'Fixed column range
'With ActiveSheet.Range("E:F")
'Using table headings
'With ActiveSheet.ListObjects("Content").HeaderRowRange
'Cell values on sheet to build column range and then search against list
With ActiveSheet.Range(vbDblQuote & fstCol & ":" & LstCol & vbDblQuote)
Set rngFound = .Find( _
What:=varList(lngCounter, 1), _
Lookat:=xlWhole, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlNext, _
MatchCase:=True _
)
If Not rngFound Is Nothing Then
If rngToDelete Is Nothing Then
Set rngToDelete = rngFound
Else
Set rngToDelete = Application.Union(rngToDelete, rngFound)
End If
strFirstAddress = rngFound.Address
Set rngFound = .FindNext(After:=rngFound)
Do Until rngFound.Address = strFirstAddress
Set rngToDelete = Application.Union(rngToDelete, rngFound)
Set rngFound = .FindNext(After:=rngFound)
Loop
End If
End With
Next lngCounter
If Not rngToDelete Is Nothing Then rngToDelete.EntireColumn.Delete
Application.ScreenUpdating = True
End Sub