像这样创建一个用户表单
然后将此代码粘贴到用户窗体代码区域。 TextBox1_KeyPress 将确保用户不会输入除数字和小数之外的任何内容。
Option Explicit
Private Sub UserForm_Initialize()
MyValue = 0: Cancelled = False
End Sub
'~~> OK Button
Private Sub CommandButton1_Click()
If Len(Trim(TextBox1.Text)) = 0 Then
MsgBox Label1.Caption
Exit Sub
End If
MyValue = Val(TextBox1.Text)
Unload Me
End Sub
'~~> CANCEL Button
Private Sub CommandButton2_Click()
Unload Me
Cancelled = True
End Sub
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Select Case KeyAscii
Case vbKey0 To vbKey9, vbKeyBack, vbKeyClear, vbKeyDelete, vbKeyLeft, vbKeyRight, vbKeyUp, vbKeyDown, vbKeyTab
If KeyAscii = 46 Then If InStr(1, TextBox1.Text, ".") Then KeyAscii = 0
Case Else
KeyAscii = 0
Beep
End Select
End Sub
现在你可以像这样使用它了。将此代码粘贴到模块中
Option Explicit
Public MyValue As Double
Public Cancelled As Boolean
Sub Sample()
Dim frm As New UserForm1
Dim Discount1 As Double
Dim Discount2 As Double
With frm
.Caption = "WhatEver Title"
.Label1.Caption = "Enter Product Discount Percentage"
.Show
End With
If Cancelled = False Then
Discount1 = MyValue
MsgBox Discount1
End If
Set frm = New UserForm1
With frm
.Caption = "WhatEver Title"
.Label1.Caption = "Enter SNS Discount net Percentage"
.Show
End With
If Cancelled = False Then
Discount2 = MyValue
MsgBox Discount2
End If
End Sub
编辑
如果需要,可以为模块代码创建一个通用函数。
Option Explicit
Public MyValue As Double
Public Cancelled As Boolean
Sub Sample()
Dim Discount1 As Double
Dim Discount2 As Double
Discount1 = ShowInputBox("WhatEver Title", "Enter Product Discount Percentage")
If Cancelled = False Then MsgBox Discount1
Discount2 = ShowInputBox("WhatEver Title", "Enter SNS Discount net Percentage")
If Cancelled = False Then MsgBox Discount2
End Sub
Private Function ShowInputBox(Title As String, Msg As String) As Double
Dim frm As New UserForm1
With frm
.Caption = Title
.Label1.Caption = Msg
.Show
End With
If Cancelled = False Then ShowInputBox = MyValue
End Function