简体   繁体   English

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

[英]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. 我有一个Excel工作表,我需要从其中将范围A:1导出到A列中的上次使用的单元格到一个xml文件。 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

Use the Workbook.Name property to get the file name. 使用Workbook.Name属性获取文件名。

FWIW, there are a few opportunities to improve your code 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:\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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM