VBA将Excel范围导出到特定目录和文件名



>我有一个 Excel 工作表,我需要从中将范围 A:1 导出到 A 列中最后一个使用的单元格到 xml 文件。如何将导出的文件名设置为与我从中导出的文件相同?

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

使用 Workbook.Name 属性获取文件名。

FWIW,有一些机会可以改进你的代码

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:exports2012" & .Parent.Name & ".xml", True)
    End With
    For i = 1 To UBound(dat, 1)
        a.WriteLine dat(i, 1)
    Next
    a.Close
End Sub

相关内容

  • 没有找到相关文章

最新更新