我目前有以下功能代码,分别引用Sheet1上的命名单元格:
Dim emp1 As Boolean
Dim emp2 As Boolean
Dim emp3 As Boolean
With Sheet1
If WorksheetFunction.CountA(.Range("AI"), .Range("AM"), .Range("AQ")) = 0 And wVOE1 = False And IsEmpty(.Range("DQ")) Then
emp1 = False
Else
emp1 = True
End If
If WorksheetFunction.CountA(.Range("FH"), .Range("FL"), .Range("FP")) = 0 And wVOE2 = False And IsEmpty(.Range("IV")) Then
emp2 = False
Else
emp2 = True
End If
If WorksheetFunction.CountA(.Range("KL"), .Range("KP"), .Range("KT")) = 0 And wVOE3 = False And IsEmpty(.Range("NZ")) Then
emp3 = False
Else
emp3 = True
End If
End With
最后,我想学习如何使用范围而不是引用单个单元格来使用CountA函数。我最初尝试了以下代码,但没有用:
Dim emp1 As Boolean
Dim emp2 As Boolean
Dim emp3 As Boolean
With Sheet1
If WorksheetFunction.CountA(Range("AI:AT")) = 0 And wVOE1 = False And IsEmpty(Sheet1.[DQ]) = True Then _
emp1 = False _
Else _
emp1 = True
If WorksheetFunction.CountA(Range("FH:FS")) = 0 And wVOE2 = False And IsEmpty(Sheet1.[IV]) Then _
emp2 = False _
Else _
emp2 = True
If WorksheetFunction.CountA(Range("KL:KW")) = 0 And wVOE3 = False And IsEmpty(Sheet1.[NZ]) Then _
emp3 = False _
Else _
emp3 = True
End With
我很难搞清楚为什么后面的代码不起作用。有没有办法参考范围?在此先感谢您的帮助。
答案 0 :(得分:2)
在第二个代码块中,附带的代码未使用With Sheet1块,因为Range()
引用没有将它们链接到With
对象的前导期
Dim emp1 As Boolean
Dim emp2 As Boolean
Dim emp3 As Boolean
With Sheet1
Debug.Print .Name, .Parent.Name '<< check it's the right sheet
' and the right workbook...
emp1 = Not (WorksheetFunction.CountA(.Range("AI:AT")) = 0 And _
wVOE1 = False And IsEmpty(.[DQ]))
emp2 = Not (WorksheetFunction.CountA(.Range("FH:FS")) = 0 And _
wVOE2 = False And IsEmpty(.[IV]))
emp3 = Not (WorksheetFunction.CountA(.Range("KL:KW")) = 0 And _
wVOE3 = False And IsEmpty(.[NZ]))
End With
答案 1 :(得分:0)
由于我的命名单元格镜像了列名,因此Excel将我的单元格范围解释为列范围,这就是我的代码无效的原因。我加了一个“。”在范围之前(如前所述),以及所有单元名称开头的“z1”,现在代码正常运行:
Dim emp1 As Boolean
Dim emp2 As Boolean
Dim emp3 As Boolean
With Sheet1
If WorksheetFunction.CountA(.Range("z1AI:z1AT")) = 0 And wVOE1 = False And IsEmpty(Sheet1.[z1DQ]) = True Then _
emp1 = False _
Else _
emp1 = True
If WorksheetFunction.CountA(.Range("z1FH:z1FS")) = 0 And wVOE2 = False And IsEmpty(Sheet1.[z1IV]) Then _
emp2 = False _
Else _
emp2 = True
If WorksheetFunction.CountA(.Range("z1KL:z1KW")) = 0 And wVOE3 = False And IsEmpty(Sheet1.[z1NZ]) Then _
emp3 = False _
Else _
emp3 = True
End With