是否有一个值可以在VBA中设置一个double,这样任何使用它进行数学运算的尝试都会抛出一个错误,导致代码行无法完成,而只是转移到下一行? / p>
上下文:
我想计算具有功能的值 彼此之间的关系(数学类型)。
目的是让一个用户填写excel单元格,其余自动填写一旦有足够的信息来定义它们 - 如果可能的话完成。
任何字段都可以按任何顺序填写......
我打算这样做:
Sub myCalculator()
On Error Resume Next '<- a key part of this
Dim startPosition As Double
Dim endPosition As Double
Dim distanceTravelled As Double
'either take the value from the cells OR define it with the
' answer ('???') I'm looking for:
If IsEmpty(Range("A1").Value) Then
startPosition = ???
Else startPosition = Range("A1").Value
EndIf
If IsEmpty(Range("A2").Value) Then
endPosition = ???
Else endPosition = Range("A2").Value
EndIf
If IsEmpty(Range("A3").Value) Then
distanceTravelled = ???
Else distanceTravelled = Range("A3").Value
EndIf
'now run through the values and fill them if we can:
startPosition = endPosition - distanceTravelled
endPosition = startPosition + distanceTravelled
distanceTravelled = endPosition - startPosition
'My idea here is that if say 'endPosition' was set to be ???
'then the first line of code would simply error, and then
'ResumeNext and then endPosition would actually be calculated,
'ready for the next line which would then be able to actually
'use it.
'then fill in the cells with the old (untouched) and new info:
Range("A1").Value = startPosition
Range("A2").Value = endPosition
Range("A3").Value = distanceTravelled
End Sub
vbNull并且似乎都没有评价为&#39; 0&#39;在某个步骤或另一个。这意味着我得到了垃圾值,其中使用了零而不是简单地抛出错误并被遗漏的行。
我应该指出,在实际案例中,我会循环执行实际数学的部分,如果第一遍中并非所有值都被填充...(同样,矛盾和定义不明确的情况将是处理。)
这个例子是基本的并且构成,它当然可以用更好的方式处理,我只是想简洁地讨论。
我不打算成为VBA专业人士;),如果有这样的解决方案,但它会被视为一种躲避,我会对此感到高兴。希望有一个基本的答案呢?
答案 0 :(得分:3)
不要使用Double
,请使用Variant
(更具体地说,Variant/Double
,也许Variant/Error
):
Sub myCalculator()
'On Error Resume Next '<- Only use this on the lines when you expect to need it
Dim startPosition As Variant
Dim endPosition As Variant
Dim distanceTravelled As Variant
'either take the value from the cells OR define it with
' an error value:
If IsEmpty(Range("A1").Value) Then
startPosition = CVErr(xlErrNA)
Else
startPosition = Range("A1").Value
End If
If IsEmpty(Range("A2").Value) Then
endPosition = CVErr(xlErrNA)
Else
endPosition = Range("A2").Value
End If
If IsEmpty(Range("A3").Value) Then
distanceTravelled = CVErr(xlErrNA)
Else
distanceTravelled = Range("A3").Value
End If
'now run through the values and fill them if we can:
On Error Resume Next
startPosition = endPosition - distanceTravelled
endPosition = startPosition + distanceTravelled
distanceTravelled = endPosition - startPosition
On Error GoTo 0
'then fill in the cells with the old (untouched) and new info:
Range("A1").Value = startPosition
Range("A2").Value = endPosition
Range("A3").Value = distanceTravelled
End Sub