Return to VBA Code Examples

VBA FreeFile Function

FreeFile Description

Returns the next valid free file number (Integer).

FreeFile Syntax

In the VBA Editor, you can type¬† “FreeFile(” to see the syntax for the FreeFile Function:

The FreeFile function contains an argument:

RangeNumber: [Optional] 0(default) to return file number in range 1-255. 1 to return file number in range 256-511.

Examples of Excel VBA FreeFile Function

Please run the following code.

Sub FreeFile_Example()
    Dim nIndex As Integer
    Dim nFileNumber As Integer
    Dim arrFileNumber(1 To 3) As Integer
    
    For nIndex = 1 To 3
        nFileNumber = FreeFile    ' Get unused file number
        arrFileNumber(nIndex) = nFileNumber
            ' number.
        Open "D:\test" & nIndex & ".txt" For Output As nFileNumber  ' Create file name.
        Write #nFileNumber, "The file number of this file is " & nFileNumber  ' Output text."
    Next nIndex
    
    For nIndex = 1 To 3
        Close arrFileNumber(nIndex)  ' Close file.
    Next nIndex
End Sub

This will create 3 files on the D drive.

test1.txt: “The file number of this file is 1”

test2.txt: “The file number of this file is 2”

test3.txt: “The file number of this file is 3”

This shows that returns 1, 2, 3 by FreeFile function.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users! vba save as


Learn More!
vba-free-addin

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

(No installation required!)

Free Download

Return to VBA Code Examples