我是VBA的新手,我正在尝试创建一个从inputBox接受0到1000之间的数字并将其转换为十六进制的宏。好吧它有效,但我努力让程序接受该范围(0 - 1000)。这就是:
我先这样做了:
Sub DecToHex()
Dim inputDec As Integer
Dim outputHex As String
inputDec = InputBox("Decimal?")
If inputDec <= 1000 And inputDec >= 0 Then
outputHex = Application.WorksheetFunction.Dec2Hex(inputDec)
MsgBox ("Hex: " + outputHex)
Else
MsgBox ("Error! Please define decimal. It must be larger than zero and less than 1001")
inputDec = InputBox("Decimal?")
outputHex = Application.WorksheetFunction.Dec2Hex(inputDec)
MsgBox ("Hex: " + outputHex)
End If
End Sub
但后来我认为inputBox给我输入字符串,所以也许我应该接受值作为字符串,所以我改变了:
Dim inputDec As Integer
'Changed to
Dim inputDec As String
对变量的控制仍然很差(即它接受-1200,同样也接受1200)。所以你能指出我做错了什么吗?也许这是工作表功能我读得不好。我知道这是新手的错误,但对我来说理解如何从inputBox控制这些输入变量非常重要。
答案 0 :(得分:2)
inputDec
为Variant
Cancel
按钮Application.InputBox
与Type:=1
一起使用,以便只接受号码。试试这个
Sub DecToHex()
Dim inputDec As Variant
Dim outputHex As String
Do
inputDec = Application.InputBox("Decimal?", Type:=1)
'~~> Handle Cancel
If inputDec = "False" Then Exit Do
If inputDec <= 1000 And inputDec >= 0 Then
outputHex = Application.WorksheetFunction.Dec2Hex(inputDec)
MsgBox ("Hex: " + outputHex)
Exit Do '<~~ Exit the loop
Else
MsgBox ("Error! Please define decimal. It must be larger than zero and less than 1001")
End If
Loop
End Sub