[英]What does this subtle VBA code change with brackets mean?
以下代碼打開文件名的默認應用程序:
Public Function OpenDefaultApplication(filename As String)
Dim sh As Object
Set sh = CreateObject("Shell.Application")
sh.Open (filename)
Set sh = Nothing
End Function
但是,從打開文件的行中除去括號意味着該文件未打開:
sh.Open filename ' does not work!
但是,如果我從函數中刪除代碼,則代碼可以成功運行而無需使用方括號。
Dim sh As Object
Set sh = CreateObject("Shell.Application")
sh.Open filename ' works if not inside a function
Set sh = Nothing
這有什么細微的區別?為什么在函數中必須使用括號?
sh.Open filename
實際上是正確的語法。
或者
Call sh.Open(filename)
原始聲明
sh.Open (filename)
計算 filename
,然后將其傳遞給sh.Open
。
如果您使用具有兩個參數的方法嘗試了此語法:
sh.SomeMethod (filename, parameter2)
您會收到語法錯誤。
所以問題是:
您將什么作為filename
傳遞給第一個函數,第二個代碼示例中的filename
是什么?
編輯
為了進一步說明,請將其添加到OpenDefaultApplication
的開頭:
Debug.Print filename
Debug.Print (filename)
並在立即窗口(Ctrl + G)中查看結果。
好吧,那很有趣。
您已經遇到了Shell.Open方法的非常奇怪的行為。
Shell.Open(ByVal vDir As Variant) As Integer
請注意,該參數定義為Variant,而不是String。
那是因為你也可以做
sh.Open 36
打開Windows文件夾。
顯然是因為這個原因, sh.Open filename
不起作用(盡管它是正確的語法),因為文件名作為引用傳遞。
sh.Open (filename)
可以工作,但是非常難看。
更好的解決方案:
1)如果堅持使用Shell.Open,則將filename
聲明為Variant。
Public Sub OpenDefaultApplication(filename As Variant)
Dim sh As Object
Set sh = CreateObject("Shell.Application")
sh.Open filename
End Sub
2)使用正確的方法打開文件Shell.ShellExecute
Public Sub OpenDefaultApplication(filename As String)
Dim sh As Object
Set sh = CreateObject("Shell.Application")
sh.ShellExecute filename
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.