excel - 如何使用现有字符串将 "yes/no"正确添加到 VBA 消息框中

标签 excel vba msgbox

我有一个基于下拉列表运行的宏。下拉列表中有三个选项。我为每个掉落创建了一条自定义警告消息,效果很好。我想在这段代码中添加"is"和“否”按钮选择,但我似乎无法让它正常工作。

我似乎只能做其中一个或。每个选择都有相同的警告消息,但带有"is"和“否”,或者每个选择都有自定义消息,但只有“确定”选项,没有"is"和“否”按钮选择。

Sub CopyRanges()

Dim message As String

If Sheets("Data").Range("D27") = "6-18" Then
    message = "You are about to change the size range, are you sure?"
Msgbox message
End If

If Sheets("Data").Range("D27") = "XS/S-L/XL" Then
    message = "You are about to change the size range to DUAL size, some POM's will not be available using the DUAL size range. Are you sure you wish to proceed?"
Msgbox message
End If

If Sheets("Data").Range("D27") = "XXS-XXL" Then
    message = "This size range is only for Fully Fashionesd Knitwear. Cut and sew styles please use the size 6-18 size range. Are you sure you wish to proceed?"
Msgbox message
End If

最佳答案

您可以向 Msgbox 添加选项(提供完整列表 here )。

通过上面提供的链接,Msgbox 的完整语法为:

MsgBox (prompt, [ buttons, ] [ title, ] [ helpfile, context ])

<小时/>

您想要访问按钮选项。实际上,它看起来像这样:

Dim Ans 'Answer
Ans = Msgbox (message, vbYesNo)

If Ans = vbYes Then
    'Do what if yes
Else
    'Do what if no
End If
<小时/>

此外,Select Case 在这里效果很好

Sub CopyRanges()

Dim message1 As String: message1 = "You are about to change the size range, are you sure?"
Dim message2 As String: message2 = "You are about to change the size range to DUAL size, some POM's will not be available using the DUAL size range. Are you sure you wish to proceed?"
Dim message3 As String: message3 = "This size range is only for Fully Fashionesd Knitwear. Cut and sew styles please use the size 6-18 size range. Are you sure you wish to proceed?"
Dim Ans as VbMsgBoxResult

Select Case Sheets("Data").Range("D27")
    Case "6-18"
        Ans = MsgBox(message1, vbYesNo)
            If Ans = vbYes Then
                'What if yes?
            Else
                'What if no?
            End If

    Case "XS/S-L/XL"
        Ans = MsgBox(message2, vbYesNo)
            If Ans = vbYes Then
                'What if yes?
            Else
                'What if no?
            End If

    Case "XXS-XXL"
        Ans = MsgBox(message3, vbYesNo)
            If Ans = vbYes Then
                'What if yes?
            Else
                'What if no?
            End If

End Select

End Sub

最后,如果您的 3 个 yes 语句导致完成 3 个本质上不同的任务,您可以考虑创建 3 个处理不同任务的子任务。然后,您可以简单地在每种情况下调用适当的子程序。它将保持代码干净,我总是鼓励分离过程以允许专门的宏,而不是一劳永逸方法

关于excel - 如何使用现有字符串将 "yes/no"正确添加到 VBA 消息框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54682793/

相关文章:

excel - 从 excel 工作簿本身向 O​​utlook 电子邮件添加附件(使用 excel 事件 'BeforeClose' )

excel - 如何通过 VBA 将一个月的 csv 文件(命名日期)导入 Excel?

python - 用作变量时如何在win32中运行VBA宏

vba - 了解从 MsgBox 返回的响应代码

windows - 如何使用 MsgBox 在 VBS 中使用用户输入正确配置条件操作?

vba - MsgBox SelectionChange 定义范围

json - 如何在不编码的情况下将 JSON 文件导入 Excel?

excel - 内部文本VBA和excel之间的冲突

sql - 连接到 SSAS 表格模型时,如何按日期而不是按字母顺序对日期列进行排序?

vba - 如何使用索引号按指定顺序从范围中选择单个单元格?