0

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
8
  • Have you set a reference to Microsoft Scripting Runtime? Commented Dec 4, 2018 at 11:05
  • @ExcelDevelopers Failure to set a reference would give a different error. Try it. Commented Dec 4, 2018 at 11:07
  • Thank you very much everyone for quick replies. I was able to solve the problem. I had to change 2 lines as follows. But can't understand why. Public FSO As New scripting.FileSystemObject Dim drv As scripting.Drive Commented Dec 4, 2018 at 11:17
  • @RonRosenfeld. I believe Excel Developers is correct. I created a new workbook and imported coderH's code. It failed as reported. I then set a reference to Microsoft Scripting Runtime and the code displayed a message box giving the free space on drive C: Commented Dec 4, 2018 at 11:19
  • scripting. tells the compiler where to look for the definitions of FileSystemObject and Drive. This avoids the need for a reference. Commented Dec 4, 2018 at 11:22

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Thank you very much for the reply. I was able to solve the problem. I had to change 2 lines as follows. But can't understand why. Public FSO As New scripting.FileSystemObject Dim drv As scripting.Drive
Do you know why I need to add scripting at the beginning?
@coderH If you do not have the reference set, then your code doesn't understand Drive. With the reference, you should not need it. Did you have any MISSING references in the list?
Yes I have one missing reference to microsoft office web components 11.0
Is it unchecked?
|
0

You need to set a reference to Microsoft Scripting Runtime. In the VBE, click on Tools, References, then scroll down to "Microsoft Scripting Runtime" and tick the box next to it.

1 Comment

Thank you for the answer. I have done it already. But this was not the reason.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.