0
我是VBA的新手,我寫了一段代碼來突出顯示我excel文件中的一些內容。但我有一個問題,我想從vba中的表標題遍歷列,而我無法做到這一點,因爲我的列號未來可能會更改。請幫忙。如何從表頭中遍歷列vba
以下是我的代碼 -
謝謝!
Sub LoopThroughRows()
Application.EnableCancelKey = xlDisabled
Dim k As Long, lastrow As Long, lastCol As Long, i As Integer, j As Integer, CurrentYear As String, TableHeader As String, CurrentQuarter As String, TargetYear As String, TargetQuarter As String
lastCol = Range("AA1").End(xlToRight).Column
With Worksheets("Sheet1")
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
Application.ScreenUpdating = False
For j = 2 To lastrow 'Starting the loop from the 2nd row
For i = 27 To lastCol ' Starting the loop from the 27th column AA1
With Worksheets("Sheet1")
If .Cells(j, i).Value > 0 Then
TableHeader = Cells(1, i).Text
Exit For
End If
End With
Next 'Loop to traverse columns ends if the condition is met
CurrentYear = Right(Cells(1, i), 2) ' Extracting the last 2 characters
CurrentQuarter = Mid(Cells(1, i), 2, 1) 'Extracting the Quarter number 2nd character
TargetYear = Right(Range("R" & j), 2) 'Extracting the last 2 characters
TargetQuarter = Right(Range("Q" & j), 1) 'Extracting the quarter number
Range("BX1" & j) = "Status"
If Not IsNull(CurrentYear & TargetYear) Then
If CurrentYear < TargetYear Then
Range("A" & j).EntireRow.Interior.ColorIndex = 3
Range("BX" & j) = "Early Start"
ElseIf TargetYear = CurrentYear Then
If CurrentQuarter < TargetQuarter Then
Range("A" & j).EntireRow.Interior.ColorIndex = 3
Range("BX" & j) = "Early Start"
End If
End If
End If
If Not IsNull(CurrentYear & TargetYear) Then
If CurrentYear > TargetYear Then
Range("A" & j).EntireRow.Interior.ColorIndex = 6
Range("BX" & j) = "Late Start"
ElseIf TargetYear = CurrentYear Then
If CurrentQuarter > TargetQuarter Then
Range("A" & j).EntireRow.Interior.ColorIndex = 6
Range("BX" & j) = "Late Start"
End If
End If
End If
If WorksheetFunction.Sum(Range("AA" & j & ":BW" & lastCol)) = 0 Then
Range("A" & j).EntireRow.Interior.ColorIndex = 5
Range("BX" & j) = "Not Started"
End If
Next ' Moving on to next row
Application.ScreenUpdating = True
End Sub
所以**表**只是正常的Rang e而不是ListObject? – PatricK
它是一個listObject – San