To get a file size using Excel VBA, the most efficient method is using the FileLen function, which returns the size of a specified file in bytes. For example, fileSize = FileLen("C:\folder\file.txt") will immediately retrieve the size of that specific file. This functionality is essential for automating data audits, monitoring log file growth, or ensuring that uploaded files meet specific size constraints before processing them within a spreadsheet.
What You'll Need
- Microsoft Excel installed on a Windows PC.
- The Developer tab enabled in the Excel Ribbon.
- A valid file path to the file you wish to measure.
- Basic familiarity with the VBA Editor (VBE).
Step-by-Step
- Enable the Developer Tab: If you do not see the Developer tab at the top of your Excel window, right-click any existing tab (like Home or Insert) and select Customize the Ribbon. In the right-hand list, check the box next to Developer and click OK.
- Open the VBA Editor: Click the Developer tab and select the Visual Basic button, or press
Alt + F11on your keyboard. This opens the integrated development environment where your code will live. - Insert a New Module: In the Project Explorer window on the left, right-click on your workbook name (e.g., VBAProject (Book1)), hover over Insert, and select Module. This creates a blank space where you can write your custom functions and macros.
- Write the Basic FileLen Code: Copy and paste the following code into the module window. This simple macro asks for a file path and displays the size in bytes:
Sub GetFileSizeBasic() Dim filePath As String Dim fileSize As Long filePath = "C:\YourFolder\YourFile.xlsx" fileSize = FileLen(filePath) MsgBox "The file size is " & fileSize & " bytes." End Sub - Implement a Dynamic File Picker: Hard-coding a file path is rarely practical. To make the tool useful, use the
Application.GetOpenFilenamemethod. Replace the previous code with this version:Sub GetFileSizeDynamic() Dim filePath As Variant Dim fileSize As Double filePath = Application.GetOpenFilename("All Files (*.*), *.*") If filePath = False Then MsgBox "No file was selected." Exit Sub End If fileSize = FileLen(filePath) MsgBox "The selected file is " & fileSize & " bytes." End Sub - Convert Bytes to KB, MB, or GB: Because
FileLenreturns bytes, the numbers can become illegible for large files. To convert the size, divide the result by 1,024. Use this logic for a professional output:Function FormatFileSize(ByVal bytes As Double) As String Dim kb As Double, mb As Double, gb As Double kb = bytes / 1024 mb = kb / 1024 gb = mb / 1024 If gb >= 1 Then FormatFileSize = Round(gb, 2) & " GB" ElseIf mb >= 1 Then FormatFileSize = Round(mb, 2) & " MB" ElseIf kb >= 1 Then FormatFileSize = Round(kb, 2) & " KB" Else FormatFileSize = bytes & " Bytes" End If End Function - Integrate the Formatter into the Main Macro: Now, update your main sub to use the formatting function. This ensures the user sees "1.5 MB" instead of "1572864 bytes":
Sub GetFileSizeFinal() Dim filePath As Variant Dim fileSize As Double filePath = Application.GetOpenFilename() If filePath = False Then Exit Sub fileSize = FileLen(filePath) MsgBox "The file size is " & FormatFileSize(fileSize) End Sub - Run and Test: Press
F5while inside theGetFileSizeFinalsubroutine or return to Excel, click the Macros button on the Developer tab, selectGetFileSizeFinal, and click Run.
Common Mistakes
One of the most frequent errors is using the wrong data type for the file size variable. Many users declare the size as an Integer. In VBA, an Integer can only hold values up to 32,767. Since file sizes are measured in bytes, even a tiny 40 KB file will cause an "Overflow" error. Always use Long or Double for file size variables to accommodate larger numbers.
Another common mistake is forgetting to handle the "Cancel" button in the file picker. If you use Application.GetOpenFilename and the user clicks Cancel, the variable returns a Boolean False. If your code immediately passes that False value into the FileLen function, VBA will throw a "File not found" or "Type mismatch" error. Always include an If filePath = False Then check before proceeding.
Users also frequently struggle with file paths. A common error is providing a path to a folder rather than a path to a specific file. FileLen is designed specifically for files; attempting to use it on a directory will result in a "Path not found" error. If you need the size of a folder, you must iterate through every file inside that folder and sum their individual sizes.
Tips
For those managing hundreds of files, instead of a manual picker, create a list of file paths in an Excel column (e.g., Column A). You can then write a loop that iterates through the rows, applies FileLen to each path, and writes the resulting size in Column B. This transforms your VBA script from a simple calculator into a powerful reporting tool.
If you are working with network drives, be aware that FileLen can be slow if the network latency is high. To optimize performance, avoid calling the function repeatedly in a tight loop if the data isn't changing. Store the value in a variable first, then perform your calculations or formatting on that variable.
To make your tool more robust, consider using the Dir function to verify the file exists before calling FileLen. While FileLen will throw an error if the file is missing, using If Dir(filePath) = "" Then allows you to provide a user-friendly warning message like "The specified file could not be located" rather than a cryptic VBA runtime error.
Troubleshooting
If your code returns a "Path not found" error, first verify the exact spelling of the file path. Check for double backslashes or missing backslashes between the folder name and the filename. Ensure that the file extension (e.g., .xlsx, .pdf, .txt) is included in the string; FileLen cannot identify a file by name alone without the extension.
If you encounter a "Permission Denied" error, it usually means the file is open in another program that has locked it, or you do not have the necessary Windows read permissions for that specific directory. Try closing the target file in all other applications and running the macro again. If the file is on a restricted corporate server, ensure your current Windows user account has "Read" access to that folder.
In cases where the code runs but the size seems incorrect, remember that FileLen reports the size on disk in bytes. This may differ slightly from the "Size on Disk" shown in Windows File Explorer, which accounts for cluster sizing. The FileLen function provides the actual logical size of the file data.
Frequently Asked Questions
Can I use this to find the size of a folder?
No, FileLen only works for individual files. To get a folder size, you must use a FileSystemObject to loop through all files within that folder and add their sizes together.
Will this work on a Mac?
No, FileLen is a Windows-specific VBA function. Mac users must use different methods, such as calling AppleScript via VBA or using the FileSystemObject alternatives if available in the Mac runtime.
What is the maximum file size VBA can measure?
By using the Double data type, VBA can handle extremely large numbers, far exceeding the size of any current hard drive. The limitation is usually the operating system's file system (e.g., NTFS) rather than VBA itself.
Does the file need to be open to get its size?
No, the file does not need to be open. In fact, it is often better to have the file closed to avoid potential "Permission Denied" errors caused by file locking.
Can I get the size of a file stored on OneDrive?
Yes, provided the file is synced to your local machine. You must provide the local path (e.g., C:\Users\Name\OneDrive\file.xlsx). If the file is "online-only," FileLen may return a size of 0 or trigger a download depending on your sync settings.