Access VBA调用Shell.Application出现对象不支持该动作错误

2017-09-06 14:29:00
zstmtony
原创
487

Access VBA使用以下的代码调用Shell.Application出现对象不支持该动作错误,错误号为445

使用各种方法尝试解决,都不得要领,最后从Items的参数的数据类型入门,解决了问题


    Set   objShell   =   CreateObject( "Shell.Application ") 
        Set   objFolder   =   objShell.BrowseForFolder(0,   "select   folder ",   0,   0) 
        Set   myFolders   =   objFolder.Items() 
        Dim   i   As   Integer 
        For   i   =   1   To   myFolders.Count 
                MsgBox   myFolders.Item(i).Path 
        Next   i 

出现的错误提示如下:


 



原因有2个

1.i 必须 定义为Variant ,不能为 Integer ,即myFolders.Item(i) 里的参数类型必须为 Variant变量类型

2.i 是从0开始 而不是 从1 开始


修改后正常的代码:

Private Sub Command6_Click()
    Set objShell = CreateObject("Shell.Application")
        Set objFolder = objShell.BrowseForFolder(0, "select   folder ", 0, 0)
        Set myFolders = objFolder.Items()
        Dim i     As Variant
        For i = 0 To myFolders.Count - 1
                MsgBox myFolders.Item(i).Path
        Next i
End Sub 


或者直接不定义对象类型,像vbscript里一样


Sub MyBrowseFolder() 
On Error Resume Next 
Dim objFolder As Folder 
Set objShell = CreateObject( "Shell.Application ") 
Set objFolder = objShell.BrowseForFolder(0, "select folder ", 0, 0) 
Dim i As Integer 
For i = 1 To objFolder.Items.Count 
Debug.Print objFolder.Items.Item(i).Path 
Next i 
End Sub 

其它也可以的代码:
Set objShell = CreateObject( "Shell.Application ") 
Set objFolder = objShell.BrowseForFolder(0, "select folder ", 0, 0) 
Set myFolders = objFolder.Items() 
Set myFolder = myFolders.Item 
For Each myFolder In myFolders 
MsgBox myFolder.Path 
Next



    分享