'Countif'结合'If'

时间:2015-09-22 14:01:24

标签: excel vba excel-vba if-statement countif

我希望使用set变量作为Countif语句的搜索条件,以在“未分配”表单的“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

1 个答案:

答案 0 :(得分:2)

我从评论中看到你修复了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