无法在Excel VBA中迭代函数返回的对象

时间:2019-01-24 06:39:18

标签: excel vba function object

我想在Excel VBA中迭代对象。但是它显示错误“运行时错误438。对象不支持此属性或方法”。

Sub FunctionTest()
    
    Dim src, dist, production As Workbook
    Dim files As Object
    
    Set dist = ThisWorkbook
    
    Set files = getFiles(dist.path)
    
    For Each file In files
    
        Debug.Print file.Name
    
    Next
    
End Sub

Function getFiles(path As String) As Object
    
    Dim fsObject, folderObj, FileObj As Object
    
    Set fsObject = CreateObject("Scripting.FileSystemObject")
    Set folderObj = fsObject.GetFolder(path)
    Set filesObj = folderObj.files
    
    Set getFiles = fsObject
    
End Function

但是如果它不是这样的返回对象,它将很好地工作。

Function getFiles(path As String) As Object
    
    Dim fsObject, folderObj, FileObj As Object
    
    Set fsObject = CreateObject("Scripting.FileSystemObject")
    Set folderObj = fsObject.GetFolder(path)
    Set filesObj = folderObj.files
    
    For Each file In filesObj
    
        Debug.Print file.Name
    
    Next
    
    Set getFiles = fsObject
    
End Function

1 个答案:

答案 0 :(得分:2)

您的代码返回了错误的对象。应该是:

 Set getFiles = filesObj