'Countif'结合'If'

我正在寻找使用一个设置variables作为Countif语句的search条件,以查找表“未分配”中“A:A”中的“用户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模块,我build议摆脱GoToCall并将所有内容embedded到完整的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