我有以下简化 VBA代码,当用户点击Excel电子表格中的按钮时,该代码会显示一个消息框:
消息框A:
Sub Message_Box_A ()
Answer = MsgBox("Do you want to continue?", vbYesNo)
If Answer = vbYes Then
Sheets("Sheet1").Range("A1").Value = 1
Else
End If
End Sub
消息框B:
Sub Message_Box_B ()
Answer = MsgBox("Do you want to continue?", vbYesNo)
If Answer = vbYes Then
Sheets("Sheet2").Range("A1").Value = 1
Else
End If
End Sub
我是否有办法全球化&#34;消息框的文本&#34;您要继续吗?&#34; 所以如果我想更改它,我不必浏览每个消息框的每个VBA代码?< / p>
答案 0 :(得分:1)
我建议使用常量。在模块插入...
Const msgContinue = "Do you want to continue?"
Sub Message_Box_A ()
Answer = MsgBox(msgContinue, vbYesNo)
If Answer = vbYes Then
Sheets("Sheet1").Range("A1").Value = 1
Else
End If
End Sub
答案 1 :(得分:0)
添加如下函数:
Function Answer() As Long
Answer = MsgBox("Do you want to continue?", vbYesNo)
End Function
然后你可以像这样使用它:
Sub Message_Box_A ()
If Answer = vbYes Then
Sheets("Sheet1").Range("A1").Value = 1
Else
End If
End Sub
修改强>:
如果我们希望自动填充功能像this answer那样作为@Peh评论。我们可以使用:
Function Answer() As VbMsgBoxResult
Answer = MsgBox("Do you want to continue?", vbYesNo)
End Function
答案 2 :(得分:0)
Terse版本:
Public Function PlsContinue() As Boolean
PlsContinue = MsgBox("Do you want to continue?", vbYesNo) = vbYes
End Function
Sub Message_Box_A()
If PlsContinue Then Sheets("Sheet1").Range("A1").Value = 1
End Sub
Sub Message_Box_B()
If PlsContinue Then Sheets("Sheet2").Range("A1").Value = 1
End Sub
编辑添加 - 灵活版本,使用任意数量的按钮,并提供不同的值:
Public Function PlsContinue() As Boolean
PlsContinue = MsgBox("Do you want to continue?", vbYesNo) = vbYes
End Function
Sub Message_Box(ByVal sht As String, ByVal cel As String, vlu As Long)
If PlsContinue Then Sheets(sht).Range(cel).Value = vlu
End Sub
Sub Message_Box_A()
Message_Box "Sheet1", "A1", 1
End Sub
Sub Message_Box_B()
Message_Box "Sheet2", "A1", 1
End Sub
Sub Message_Box_C()
Message_Box "Sheet1", "A2", 2
End Sub
答案 3 :(得分:0)
我只是在猜测,但也许以下代码可能对您有所帮助(特别是如果您有太多Message_Box_X ()
Subs)。
Private Sub CommandButton1_Click()
WhichButton = "Sheet1"
Message_Box (WhichButton)
End Sub
Private Sub CommandButton2_Click()
WhichButton = "Sheet2"
Message_Box (WhichButton)
End Sub
Sub Message_Box(WB As String)
msgContinue = "Do you want to continue?"
Answer = MsgBox(msgContinue, vbYesNo)
If Answer = vbYes Then
Sheets(WB).Range("A1").Value = 1
Else
End If
End Sub