【问题标题】:If and ElseIf Statement in VBAVBA 中的 If 和 ElseIf 语句
【发布时间】:2016-11-21 03:08:06
【问题描述】:

我正在使用 VBA 为我的 word 文档制作一个表单。我边走边学。我有一个组合框,您可以在其中从列表中选择一个项目。基本上,如果选择了“Homestretch”项,我希望文档打印出 4 个副本,而对于选择或键入组合框中的所有其他内容,我希望打印出 3 个副本。

当我选择 Homestretch 时,我可以完美打印出 4 份副本,但如果我选择其他任何内容,它就不会打印。另请注意,这是在命令按钮单击功能下,我只希望在选中 ckbPrint 复选框时执行。这是下面的代码。谢谢。

If Me.ckbPrint.Value = True Then
If cbxCarrier.Value = "Homestretch" Then
     ActiveDocument.PrintOut copies:=4
ElseIf cbxCarrier.Value <> "Homestretch" Then
ElseIf Me.ckbPrint.Value = True Then
     ActiveDocument.PrintOut copies:=3
End If
End If 

【问题讨论】:

    标签: vba if-statement basic


    【解决方案1】:

    您的代码应用了太多测试。您可以将其简化为以下内容:

    Dim copies As Long
    
    If Me.ckbPrint Then
        If cbxCarrier.Value = "Homestretch" Then
            copies = 4
        Else
            copies = 3
        End If
        ActiveDocument.PrintOut copies:=copies
    End If
    

    【讨论】:

    • 感谢避免显式的{bool-expression} = True 测试,但是……您依赖ckbPrint 的默认成员值,但显式检查cbxCarrier.Value。我也会提前使用If Not Me.ckbPrint.Value Then Exit Sub 退出,并删除缩进级别。赞成删除 ActiveDocument.PrintOut 重复。干得好!
    • 谢谢!这非常有效,很容易理解这里发生了什么。我想我只是想多了。再次感谢!
    【解决方案2】:

    应该是这样的

    If Me.ckbPrint.Value = True Then
        If cbxCarrier.Value = "Homestretch" Then
             ActiveDocument.PrintOut copies:=4
        ElseIf cbxCarrier.Value <> "Homestretch" Then
             'put your inner else statement here. If none, then remove it
        End If 
    ElseIf Me.ckbPrint.Value = False Then 'this else is connected with first if
     ActiveDocument.PrintOut copies:=3
    End If
    

    如果不是你想要的,就改变语句,但是 if 和 elseif 是如何工作的

    【讨论】:

    • 由于 [缺少] 缩进更难分辨,但是当 Not Me.ckbPrint.Value 时,OP 的代码不会打印任何内容。
    【解决方案3】:

    对于简单的If ... Then 情况,您只需要在分配两个值之一之间做出决定,IIf() 函数可以使您的代码更简单:

    If Me.ckbPrint Then ActiveDocument.PrintOut _
         copies:=IIf(cbxCarrier.Value="Homestretch", 4, 3)
    

    语法:IIf(test, if_test_true, if_test_false)

    【讨论】:

    • 据作者介绍,他是初学者。您能否添加更多解释,为什么您的代码行会有所帮助?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多