2015-05-23 182 views
2

我是VBA的新手,我试图创建一个从inputBox接受0到1000之间的数字并将其转换为十六进制的宏。它的工作原理,但我努力让程序接受范围(0 - 1000)。这是发生了什么:inputBox Excel VBA整数问题

  • 如果我输入-1它会引发错误;
  • 如果我输入-1001,它会抛出一个FFFFFFFC17;
  • 如果我输入超过1000的任何值,它不会抛出一个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 

但后来我想好了输入框让我输入字符串,所以也许我应该接受值的字符串,所以我改变:

Dim inputDec As Integer 
'Changed to 
Dim inputDec As String 

哪个仍然对变量做了很差的控制(例如,它接受-1200和1200)。所以你能指出我做错了什么?也许这是我阅读不好的工作表功能。我知道这是新手的错误,但了解如何从inputBox控制这些输入变量对我来说很重要。

回答

2
  1. 您需要声明inputDec作为Variant
  2. 你需要处理的Cancel按钮
  3. 您需要将代码放在一个循环,这样,当用户输入无效号码,输入框可以弹出再次。
  4. 您需要使用Application.InputBoxType:=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 
+0

这工作作为一个魅力:)谢谢! –

+0

很高兴能有帮助:) –

+0

我会给+1,但我没有足够的代表! –