VBA - 访问FileSystemObject而不将其作为对象进行调整

时间:2017-06-29 14:31:23

标签: vba

我想知道你是否可以在不变暗的情况下访问对象。 示例如下:

为了访问FileSystemObject,我将按以下方式访问它:

Dim fso As Object
fso = CreateObject("Scripting.FileSystemObject")

    If fso.FolderExists("C:\Folder")
        msgbox "Folder exists"
    End If

我正在寻找一种方法来访问它而不必调暗它。 有点像:

    If Scripting.FileSystemObject.FolderExists("C:\Folder")
        msgbox "Folder exists"
    End If

我已将[Microsoft Scripting Runtime]添加为我的项目的参考,如果这对我的问题有帮助。

2 个答案:

答案 0 :(得分:4)

以下内容可以正常使用:

Set myFolder = CreateObject("Scripting.FileSystemObject").GetFolder("C:\temp\")

WScript.Echo myFolder.Files.Count

同样,您的示例可能是:

If CreateObject("Scripting.FileSystemObject").FolderExists("C:\Folder\") Then
    ' do something
End If

这也可以。

您并不特别需要与filesystemobject本身关联的对象。但是,如果你使用的是Option Explicit(我想不出一个好的理由),那么强制使用之前声明你的变量。

答案 1 :(得分:4)

这也是有效的:

后期绑定:

With CreateObject("Scripting.FileSystemObject")
    If Not .FolderExists(path_) Then .CreateFolder path_
End With

早期绑定(需要引用脚本库):

With New Scripting.FileSystemObject
    If Not .FolderExists(path_) Then .CreateFolder path_
End With