首页 > 解决方案 > 如何使用CountA?

问题描述

我必须在我的宏中添加一条规则,检查 Sheet1 中 A1:Z1 范围内是否有空白单元格。如果是,它会运行进一步的代码。如果不是,它将显示 MsgBox 并停止宏。我写

    If WorksheetFunction.CountA(Worksheets("Sheet1").Range("A1:Z1")) Then
 MsgBox"ERROR"
 
 Else

rest of my code

 End If

不幸的是,即使是 A1:Z1 中的那些单元格也是空白的,我看到 MsgBox

请你帮助我好吗?

标签: excelvba

解决方案


我喜欢跳过工作表函数并做纯 VBA。

'set worksheet
dim ws as worksheet
set ws = worksheets("Sheet1")

'init counter
dim empty as integer
empty = 0


'loop cells
for x = 1 to 26
    'check row 1 columns 1 to 26
    if trim(ws.cells(1, x)) = "" then
        empty = empty + 1
    end if
next x

'check empty
if empty > 0 then
    'extra code
Else
    msgbox "no empty found"
end if

推荐阅读