将函数定义为对象在函数中创建对象并从函数中返回对象

时间:2019-05-08 22:59:24

标签: excel vba

在excel VBA中,将函数定义为对象,然后在函数中创建一个对象并从该函数返回该对象。 我有将对象设置为函数中目录的代码,我想通过函数返回该对象。

我有将对象设置为函数中目录的代码,我想通过函数返回该对象。 附件中的代码出现以下错误。 未设置对象变量或带块变量。 执行“结束功能”后,会发生这种情况 如果将函数更改为子函数,并且该对象通过ByRef传递并返回,则该例程起作用。

Sub Main()
    Dim oDirectories     As Object
    Dim sDirectory      As String
    sDirectory = "C:\Users"
    oDirectories = ListDirectories(sDirectory)
end sub

Private Function ListDirectories(ByVal sPath As String) As Object

    Dim oFSO        As Object
    Dim a           As String

' Function does not work without the following line
    ChDir sPath
' Verify that system can find the directory
    a = CurDir()

    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oFiles = oFSO.GetFolder(sPath).SubFolders

   Set ListDirectories = oFiles

End Function

0 个答案:

没有答案