我有一個約12張工作簿。我試圖將條件格式和數據驗證應用於從第2頁到第6頁上的從E到Y的交替行。Excel VBA循環通過一些工作表,但不是全部
驗證和格式工作完美,但表循環給了我很多問題。
它始終將循環應用於工作表1,並不總是將其應用於從2到6的每個工作表,儘管沒有碰到的工作表發生更改。
我不知所措。一些代碼與錄製宏功能製作的,所以我敢肯定,這是低效和龐大的,但這裏的代碼:
Sub ListCF()
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim cl As Variant
Dim Row As Variant
Dim ws As Worksheet
For i = 2 To 6
With ThisWorkbook.Worksheets(i)
Worksheets(i).Activate
Cells.Select
Selection.FormatConditions.Delete
Selection.Validation.Delete
Selection.NumberFormat = "General"
For j = 5 To 23 Step 2
Range(Cells(2, j), Cells(50, j)).Select
With Selection.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=Reference!$A$2:$A$50"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
Next j
For k = 6 To 24 Step 2
cl = Mid(Cells(2, k).Address, 2, 1)
Range("$" & cl & 2, "$" & cl & 50).Select
Selection.NumberFormat = "m/d/yyyy"
'With Range(Cells(2, k), Cells(50, k))
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$" & cl & 2 & ">(TODAY()-60)"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font
.Bold = True
.Italic = False
.Color = -16776961
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=$" & cl & 2 & "<(TODAY()-60)"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font
.Bold = False
.Italic = False
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
'End With
Range(Cells(2, k), Cells(50, k)).Select
Selection.NumberFormat = "m/d/yyyy"
Next k
End With
Next i
End Sub
你有太多的'Select'和'Selection' –
'隨着ThisWorkbook.Worksheets(我)' - 你不是在所有的循環 –
'工作表使用這個( i)'表示按照Tab鍵順序從左到右數的第i個工作表。這是你期望的順序嗎?或者您是否嘗試訪問名爲「Sheet2」,「Sheet3」,「Sheet4」,「Sheet5」和「Sheet6」的工作表? – YowE3K