By using expertatexcel.com you agree to our cookie policy, We and our partners operate globally and use cookies, for multiple purposes

expertatexcel.com

 


Create a file

Through Excel/VBA you can easily write code to create files on your computer, or on a network computer or even Sharepoint.

Local files are usually named "C:\file....txt"

To create a text file which has the "txt" file suffix you could use the following code:


' Call to create

x = bOpenSeqFile("C:\temp\Atestfile.txt","O")



Public Function bOpenSeqFile(vsFile As String, vsType As String) As Integer
'Version: 1.000
'Sequential file wrapper for opening, creating, readonly files

    Dim gscurfile As String
    ' This function is called to open a sequential file
    ' It returns the file number
    On Error GoTo ErrHandler

    Dim iFreeFile As Integer

    iFreeFile = FreeFile
    If Err = 67 Then 'What is this
       ' AppMsgbox Err & " " & Error & " during bOpenSeqFile of " & vsFile & " for " & vsType
        bOpenSeqFile = -1 * Err
        Exit Function
    End If

Retry:
    gscurfile = vsFile  ' set for error handling
    Select Case vsType
        Case "I"
            Open vsFile For Input As #iFreeFile
        Case "O"
            Open vsFile For Output As #iFreeFile
        Case "U"
            Open vsFile For Random As #iFreeFile
        Case "B"
            Open vsFile For Binary As #iFreeFile
        Case "A"
            Open vsFile For Append As #iFreeFile
        Case Else
            '@@ handle unexpected condition
    End Select
    bOpenSeqFile = iFreeFile
    Exit Function
    
ErrHandler:
    If Err.Description = "File not found" Then
        Open vsFile For Output As #iFreeFile
        Close #iFreeFile
        Resume
    ElseIf Err <> 0 Then
        bOpenSeqFile = -1 * Err
    
    End If
End Function