InputBox confusing Decimal entries with strings

2019-07-24 01:31发布

I am trying to use an InputBox function to be able to have a user input data. However, the data mainly consists of decimal values. When I am testing my program and I go to subtract two values, both entered from InputBox, it does not perform a mathematical operation.

thckmax = InputBox("What is the maximum nominal thickness?", "Enter Max Nominal Thickness Measurement")
thckmin = InputBox("What is the minimum nominal thickness?", "Enter Min Nominal Thickness Measurement")
thcknom = (thckmax + thckmin)

If I were to enter .05 and .04 respectively, it displays the preceding code as:

thcknom is .05.04

I am trying to perform the mathematical operation, addition, to the two variables; however, it is just "adding" the two strings side-by-side. How do I fix this issue?

标签: excel vba
2条回答
我命由我不由天
2楼-- · 2019-07-24 01:47

You need to declare the variables as either Double or Single, depending on the expected input:

Sub t()
Dim thckmax As Double, thckmin As Double, thcknom As Double
thckmax = InputBox("What is the maximum nominal thickness?", "Enter Max Nominal Thickness Measurement")
thckmin = InputBox("What is the minimum nominal thickness?", "Enter Min Nominal Thickness Measurement")
thcknom = (thckmax + thckmin)
Debug.Print thcknom
End Sub

See VBA's data types for more info.

Also, I suggest adding Option Explicit to the very top of your modules, which forces you to declare all variables.

查看更多
【Aperson】
3楼-- · 2019-07-24 02:06

InputBox allows you to define the input type. Since you did not specify one, the default is used, which is TEXT.
Something like

thckmax = Application.InputBox(Prompt:="What is the maximum nominal thickness?", Type:=1)

guarantees you get a number, eventually preventing decimal symbol confusion.

查看更多
登录 后发表回答