excelexport-to-textvba

VBA Export Excel Range to specific directory and file name


I have an Excel worksheet from which I need to export range, A:1 to last used cell in column A, to an xml file. How do you set the exported file name to be the same as the file I exported from?

Sub exportxmlfile()
Dim myrange As Range

Worksheets("xml").Activate
Set myrange = Range("A1:A20000")
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.CreateTextFile("C:\exports\2012\test.xml", True)
For Each c In myrange
a.WriteLine (c.Value)
Next c
a.Close
End Sub

Solution

  • Use the Workbook.Name property to get the file name.

    FWIW, there are a few opportunities to improve your code

    Sub exportxmlfile()
       ' declare all your variables
        Dim myrange As Range
        Dim fs As Object
        Dim a As Object
        Dim dat As Variant
        Dim i As Long
    
        ' No need to activate sheet
        With Worksheets("xml")
            ' get the actual last used cell
            Set myrange = .Range("A1", .Cells(.Rows.Count, 1).End(xlUp))
            ' copy range data to a variant array - looping over an array is faster
            dat = myrange.Value
            Set fs = CreateObject("Scripting.FileSystemObject")
            ' use the excel file name
            Set a = fs.CreateTextFile("C:\exports\2012\" & .Parent.Name & ".xml", True)
        End With
        For i = 1 To UBound(dat, 1)
            a.WriteLine dat(i, 1)
        Next
        a.Close
    End Sub