将变体添加到VBA中的问题
我对VBA编程相当陌生,以及不同的数据types是如何工作的,所以我遇到了一个问题。 我在rng1
添加了两个不同的数字( rng
和rng1
)。 如果用户按下取消程序closures和表locking。 如果我使用例如一个整数而不是变体,我不能运行closures代码。 然而,当我尝试做rng + rng1
它不会添加它们,而是粘在一起,即如果grp = 2
和grp1 = 3
则grp + grp1 = 23
。 这与我的情节function混乱。 所以我希望有人能帮我找出正确的数据types来使用? 或者对问题有不同的解决scheme。 代码可以在下面看到。
dim grp As variant dim grp1 As variant Application.DisplayAlerts = False On Error Resume Next grp = InputBox("Enter No in Group 1") On Error GoTo 0 Application.DisplayAlerts = True If grp = "" Then MsgBox ("User canceled!") ActiveSheet.Protect Password:="..." Exit Sub End If Application.DisplayAlerts = False On Error Resume Next grp1 = InputBox("Enter No in Group 2") On Error GoTo 0 Application.DisplayAlerts = True If grp1 = "" Then MsgBox ("User canceled!") ActiveSheet.Protect Password:="..." Exit Sub End If ActiveSheet.ChartObjects("Chart1").Activate With ActiveChart I = 3 Do Until I = grp + 3 ActiveChart.FullSeriesCollection(I).Select ActiveChart.SeriesCollection(I).Select With Selection .Border.LineStyle = xlContinuous .Border.Color = RGB(0, 255, 0) .MarkerBackgroundColor = RGB(0, 255, 0) .MarkerForegroundColor = RGB(0, 255, 0) End With I = I + 1 Loop j = grp + 3 Do Until j = grp + grp1 + 3 ActiveChart.SeriesCollection(j).Select With Selection .Border.LineStyle = xlContinuous .Border.Color = RGB(0, 0, 255) .MarkerBackgroundColor = RGB(0, 0, 255) .MarkerForegroundColor = RGB(0, 0, 255) End With j = j + 1 Loop
它不会添加它们,而是将它们粘合在一起,即如果
grp = 2
和grp1 = 3
则grp + grp1 = 23
InputBox
返回一个String
types。 很多人没有意识到的是,你可以使用&
或+
运算符来组合string,这就是你正在做的事情:
"2" + "3" = "23" '// equivalent to "2" & "3"
鉴于:
2 + 3 = 5
所以,因为你的参数是String
types的,所以+
运算符假设你正在试图合并它们,没有向Int
或Long
或Double
隐式types转换,因为这个运算符对组合string是完全有效的,这就是你给它:)
注意:通常build议只使用&
运算符,这样就不会混淆string,而添加长/整数值。
为了将结果input作为数字types处理 (即执行加法或其他算术运算),则需要使用数字数据( Integer/Long/Double
)而不是String
types。 你可以做一个明确的types转换:
Dim grp as Long grp = CLng(InputBox("Enter No in Group 1"))
或者,最好使用InputBox
函数的Type
参数 :
Dim grp as Long grp = InputBox("Enter No in Group 1", Type:=1)
相同的grp2
。
因为这两个input都不能为0,所以这对你来说可能就好了:
Dim dInput1 As Double Dim dInput2 As Double 'Use Application.InputBox with Type 1 to force a numeric entry dInput1 = Application.InputBox("Enter No in Group 1", Type:=1) If dInput1 = 0 Then Exit Sub 'Pressed cancel 'Use Application.InputBox with Type 1 to force a numeric entry dInput2 = Application.InputBox("Enter No in Group 2", Type:=1) If dInput2 = 0 Then Exit Sub 'Pressed cancel 'A simple example showing the values and their sum MsgBox dInput1 & " + " & dInput2 & " = " & dInput1 + dInput2
这里有一个关于Application.InputBox的更多信息的链接