Vba 是否可以有一个动态检查变量的函数?
我有一个VBA代码,看起来像这样:Vba 是否可以有一个动态检查变量的函数?,vba,excel,Vba,Excel,我有一个VBA代码,看起来像这样: user enters value for variable isnumeric(this variable) user enters value for another variable isnumeric(this variable now) user enters value for a third variable isnumeric(this third variable) 有没有一种方法可以用以下内容来代替: user enters vari
user enters value for variable
isnumeric(this variable)
user enters value for another variable
isnumeric(this variable now)
user enters value for a third variable
isnumeric(this third variable)
有没有一种方法可以用以下内容来代替:
user enters variable
call CheckIfThisIsNumeric
go back to other function and repeat this process several times
这样我就不用在我的程序中写一百万次IsNumeric了
如果这是非正式的,请道歉。在我看来,唯一的方法就是将变量放入全局变量中。一件坏事有两个原因:
Public myVariableforCheckingNumericity As Variant
(.../...)
myVariableforCheckingNumericity = ThisVariable
If CheckIfThisIsNumeric Then......
Function CheckIfThisIsNumeric () As Boolean
CheckIfThisIsNumeric = IsNumeric(myVariableforCheckingNumericity)
End Function
然而,正如评论者所说,总的来说,好处是负面的。为什么要将对IsNumeric的调用封装在另一个做同样事情的方法中?或者我不明白你想做什么。如果你不多次调用IsNumeric,你只会多次调用你的函数……调用它仍然会产生更简洁的代码,尽管这很有道理。我的问题是:有没有办法让哪个变量被测试为IsNumeric变量?我的观点是,如果你有一个函数
IsNumeric(toTest As String)
,你把它包装在一个函数CheckIfThisIsNumeric(toTest As String)
中,然后只调用IsNumeric(toTest)
,你得到了什么?您添加了一个不必要的步骤并增加了开销。您需要编写调用CheckNum
的次数与编写IsNumeric()
的次数相同。。。那么好处是什么呢?@ThomasShera如果您将变量声明为任何数字类型,那么如果用户尝试分配字符串,就会出现错误。现在对你有意义了吗?