Home » excel » excel – VBA:Iterate through all columns of a worksheet

excel – VBA:Iterate through all columns of a worksheet

Posted by: admin May 14, 2020 Leave a comment

Questions:

Within the worksheet that the macro is defined in, id like to iterate through all the columns and save the ones that are filled in an array.

x = IIf(WorksheetFunction.CountA(Columns("C")) > 0, 1, 0)

This is an example of how I’d check if the column is empty. It returns 1 if the column is filled and 0 if it is empty.

Another thing that I’d like to know is how I could give and get the column name as a variable rather than hardcoded string ("C" as you see above).

Id like the array to look like:
("A", "B", "C", "E", "G", "H", "I")

How to&Answers:

This code should do the trick:

Dim DataCols() As String
Dim strTemp As String
Dim strCol As String
Dim i As Long

For i = 1 To ActiveSheet.UsedRange.Columns.Count
    If WorksheetFunction.CountA(Columns(i)) > 0 Then
        strCol = Columns(i).Address
        strTemp = strTemp & Mid(strCol, 2, InStr(strCol, ":") - 2) & "|"
    End If
Next i
strTemp = Left(strTemp, Len(strTemp) - 1) 'Trim trailing | 

DataCols = Split(strTemp, "|")
  • The For..Next loop iterates through all columns in the active worksheet.
  • Using WorksheetFunction.CountA as you also used in your example it is then determined whether the current column has any data in it.
  • If the column contains data we get its address (Which will be a string in the format $A:$A) and use Mid(..) to get the letters between the $ character and the : character.
  • Append that column letter to strTemp, followed by a Pipe | which we will later use as a delimiter.
  • The Dynamic Array DataCols is then populated by using the Split function on strTemp to return a string array (delimited by the |s we included).

Hope this helps!