使用one of my previous questions的智慧,我写的是:
Flt
检查AC
是否在给定数字之间AC
号码范围,请检查Bkd
是否超过给定数量请注意
AC
是F栏; Bkd
是H列; Flt
是G列AC
和Bkd
,如下面If
的每一行所示目前,这会生成错误91,“未设置块”或“类型不匹配”错误。我已经回顾了我之前的问题,并从功能完备的代码中获取了大部分内容,但似乎无法使其正常工作。建议?
LastRow = Range("G" & Rows.Count).End(xlUp).Row
AC = Range("F9:F" & LastRow)
Bkd = Range("H9:H" & LastRow)
With ActiveSheet.Columns("G").SpecialCells(xlCellTypeConstants, xlNumbers)
If (AC > "199" And AC < "500" And Bkd > "145") Or _
(AC > "499" And AC < "600" And Bkd > "130") Or _
(AC > "599" And AC < "700" And Bkd > "100") Or _
(AC > "699" And AC < "800" And Bkd > "115") Then
.Font.Color = vbWhite
.Interior.Color = vbBlack
End If
End With
这是我在下面的评论中引用的另一个尝试的代码块。
Dim AC, Bkd, Flt As Range
LastRow = Range("G" & Rows.Count).End(xlUp).Row
AC = Range("F9:F" & LastRow)
Bkd = Range("H9:H" & LastRow)
For Each Flt In ActiveSheet.Columns("G").SpecialCells(xlCellTypeConstants, xlNumbers)
With Flt
If (AC > "199" And AC < "500" And Bkd > "145") Or _
(AC > "499" And AC < "600" And Bkd > "130") Or _
(AC > "599" And AC < "700" And Bkd > "100") Or _
(AC > "699" And AC < "800" And Bkd > "115") Then
.Font.Color = vbWhite
.Interior.Color = vbBlack
End If
End With
Next Flt
答案 0 :(得分:0)
如果你告诉错误出现在哪一行会更容易。
使用此代码定义范围:
Set LastRow = Range("G" & Rows.Count).End(xlUp).Row
Set AC = Range("F9:F" & LastRow)
Set Bkd = Range("H9:H" & LastRow)
答案 1 :(得分:0)
我在你的代码中看到了几个“红旗”。
"199"
而不是199
进行比较。我假设单元格将包含数字199,而不是文本字符串“199”。如果它确实是文本字符串,那么在下面的代码中,您应该更改,例如Flt > 199
到CLng(Flt) > 199
.SpecialCells(xlCellTypeConstants, xlNumbers)
最终会影响整个工作表。它应该被淘汰。您尚未提供具有预期结果的特定测试数据。我取得了这些成果......
...来自此代码,解决上述问题......
Sub test()
Dim AC As Range, Bkd As Range, ClrRng As Range
Dim Flt As Range
Dim mySht As Worksheet
Dim LastRow As Long
Set mySht = Worksheets("Sheet1") ' <- change this to the sheet you want to use
LastRow = mySht.Range("G" & mySht.Rows.Count).End(xlUp).Row
Set AC = mySht.Range("F9:F" & LastRow)
Set Bkd = mySht.Range("H9:H" & LastRow)
Set ClrRng = mySht.Range("G9:G" & LastRow)
For Each Flt In AC
If (Flt > 199 And Flt < 500 And Bkd(Flt.Row - 8, 1) > 145) Or _
(Flt > 499 And Flt < 600 And Bkd(Flt.Row - 8, 1) > 130) Or _
(Flt > 599 And Flt < 700 And Bkd(Flt.Row - 8, 1) > 100) Or _
(Flt > 699 And Flt < 800 And Bkd(Flt.Row - 8, 1) > 115) Then
With ClrRng(Flt.Row - 8, 1)
.Font.Color = vbWhite
.Interior.Color = vbBlack
End With
End If
Next Flt
End Sub