inputBox Excel VBA整数问题

我是VBA的新手,我试图创build一个从inputBox接受0到1000之间的数字并将其转换为hex的macros。 那么它的工作原理,但我正在努力保持程序接受范围(0 – 1000)。 这是发生了什么事情:

  • 如果我input-1它会引发一个错误;
  • 如果我input-1001,则抛出一个FFFFFFFC17;
  • 如果我input1000以上的任何值,它不会抛出一个MsgBox(我不熟悉现在在Excel中导致错误)。

我先这样做了:

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 

但后来我认为,input框给我的input作为string,所以也许我应该接受值的string,所以我改变了:

 Dim inputDec As Integer 'Changed to Dim inputDec As String 

对variables的控制仍然很差(即它接受-1200,也就是1200)。 那么你能指出我做错了什么吗? 也许这是工作表函数,我不是很好的阅读。 我知道这是新手的错误,但是了解如何从inputBox控制这些inputvariables是很重要的。

  1. 你需要声明inputDec As Variant
  2. 您需要处理Cancelbutton
  3. 您需要将代码放在一个循环中,以便当用户input无效的数字时,input框可以再次popup。
  4. 您需要使用Application.InputBox Type:=1 Application.InputBox ,以便只能接受数字。

尝试这个

 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