如何使用现有字符串正确将“是/否”添加到VBA消息框中

时间:2019-02-14 03:28:20

标签: excel vba msgbox

我有一个基于下拉列表运行的宏。下拉列表中有三个选项。我为每滴墨滴创建了一个自定义警告消息,效果很好。我想在此代码上添加“是”和“否”按钮选择,但我似乎无法使其正常工作。

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

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

1 个答案:

答案 0 :(得分:3)

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

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

  

MsgBox 提示,[按钮,] [标题,] [帮助文件,   上下文])


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

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个处理不同任务的子。然后,您可以简单地在每种情况下调用相应的子程序。它将保持这段代码的整洁,我一直鼓励分离过程以允许使用专门的宏,而不是 one-does-all 方法