Search code examples
excelvbafilesystemobject

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


When I try to run this code, I get an error like this

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

Solution

  • I assume you have set a reference to Microsoft Scripting Runtime, otherwise the error would be something like User defined type not defined.

    In the VBA Editor, go to Tools/References and look for a Reference with MISSING. Uncheck that and see if it works.