我在Excel 2016中编写脚本并遇到一些奇怪的行为,具体取决于我如何定义变量。我在下面创建了一些示例代码来重现错误。
我想知道这是一个已知的VBA错误还是我做错了什么?
Sub IWork()
Dim name As String ' name is declared alone
Dim lastname As String
name = "Ben"
Hello name:=name
End Sub
' IFail creates a compile error
' ByRef argument type mismatch
Sub IFail()
Dim name, lastname As String ' name is declared with other variables
name = "Ben"
Hello name:=name
End Sub
Sub Hello(ByRef name As String)
' Do something with name ...
Debug.Print "Hello " & name
End Sub
答案 0 :(得分:3)
当你这样定义它们时:
Dim name, lastname As String
你实际上定义的是这样的:
Dim name As Variant, lastname As String
你想要像这样定义它们
Dim name As String, lastname As String
就个人而言,我更喜欢在不同的行上定义它们。
Dim name As String
Dim lastname As String
此外,我喜欢在变量名前加上一个字母,提醒我它是什么类型的变量,并防止变量名称与Name
等关键词混淆 - 就像这样:
Dim sName As String
Dim sLastname As String
但这只是我的偏好。