创建文件系统对象的新实例时出现编译错误

I get compile error when create new instance of file system object

当我尝试运行这段代码时,我得到了这样的错误

Compile error
Can't find a project or library.

Public FSO As New FileSystemObject

Sub DiskSpace()
    Dim drv As Drive
    Dim Space As Double
    Set drv = FSO.GetDrive("C:") ' Creating the the Drive object

    Space = drv.FreeSpace
    Space = Space / 1073741824 'converting bytes to GB
    Space = WorksheetFunction.Round(Space, 2) ' Rounding

    MsgBox "C: has free space = " & Space & " GB"
End Sub

您需要设置对 Microsoft Scripting Runtime 的引用。在 VBE 中,单击“工具”、“参考”,然后向下滚动到 "Microsoft Scripting Runtime" 并勾选旁边的框。

我假设您已经设置了对 Microsoft Scripting Runtime 的引用,否则会出现类似于未定义用户定义类型的错误。

在 VBA 编辑器中,转到 Tools/References 并查找带有 MISSING 的参考。取消选中它,看看它是否有效。