Search code examples
vbacolumnsorting

Indexing through an array by column number


I've looked up info with regards to column attributes. I'm trying to perform some insertions and copying of information within an array. The crux of my issue is that I want o nest some actions within a loop, so I need to index the column by a number not letter.

The first thing I do is find a starting point based upon a header name:

Dim EnvCondCol As String
Dim EnvCondColN As Long
Dim lColVVS As Integer
lColVVS = VET_VS.UsedRange.Columns.Count ' finds last column
For n = 1 To lColVVS
    If UCase(VET_VS.Cells(3, n).Value) Like "*ENVIRONMENTAL CONDITION*" Then ' All Caps when using "like"
        EnvCondCol = Split(VET_VS.Cells(3, n).Address, "$")(1)
        EnvCondColN = Range(EnvCondCol & 1).Column
        Exit For
    End If
Next n

This works and when I watch EnvCondCol and EnvCondColN is can see EnvCondCol = "I" and EnvCondColN = "9" Eventually, I want to insert a new column, and this line generates a syntax error:

VET_VS.Range(Columns.(EnvCondColN)).EntireColumn.Insert

When I watch EnvCondColN, it is a number, and I have tried changing the dim to other types, such as integer

Also elsewhere, I want to copy information from a cell into another cell from within a loop. This generates a syntax error.

VET_VS.Range(Columns.(EnvCondColN + i)).Copy VET_VS.Range(Columns.(EnvCondColN + j))

If I replace EnvCondColN with a value like 5, then this works. Example: VET_VS.Range(Columns.(5)).EntireColumn.Insert

Why isn't the variable working as a column reference??

Thank you all for looking!


Solution

  • change

     VET_VS.Range(Columns.(EnvCondColN)).EntireColumn.Insert
    

    to

     VET_VS.Columns(EnvCondColN).EntireColumn.Insert