'Countif' 结合 'If'

'Countif' combined with 'If'

我希望使用一个集合变量作为 Countif 语句的搜索条件,以在 sheet "Unallocated" 中查找 "A:A" 中的 "User 1"。如果 Countif 返回值为 0,我想跳过 运行 代码,而是继续执行下一个 Countif(目前没有,但一旦我得到这个逻辑正确,我将使用重复了几次)。

这是我目前的情况:

Private Sub CommandButton21_Click()

Dim iVal As Integer
Dim User As String
'Dim Wkb As Workbook 'to be used later

User = "User 1"
iVal = Application.WorksheetFunction.CountIf(Worksheets("Unallocated").Range("A2:A"), "User 1")
If iVal = 0 Then GoTo ALabel
Call User1Allo 'macro held in a module
MsgBox ("It Tried to run the macro")
ALabel:
MsgBox ("It Didn't try to run the macro")

'For Each Wkb In Workbooks 'to be used later
'        If Not Wkb.ReadOnly And Windows(Wkb.Name).Visible Then 'to be used later
'            Wkb.Save 'to be used later
'        End If 'to be used later
'    Next 'to be used later


End Sub

我从评论中看到您修复了 A2:A 语法。现在为了让代码真正跳过 User1Allo 模块,我建议去掉 GoToCall 并将所有内容嵌入完整的 If ... Then ... Else 块中。

见下文:

User = "User 1"
iVal = Application.WorksheetFunction.CountIf(Worksheets("Unallocated").Range("A:A"), User)

If iVal = 0 Then
    MsgBox ("It Didn't try to run the macro")
Else
    User1Allo 'macro held in a module
    MsgBox ("It Tried to run the macro")
End If