2

我有一个 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:\exports\2012\test.xml", True)
For Each c In myrange
a.WriteLine (c.Value)
Next c
a.Close
End Sub
4

1 回答 1

0

使用该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:\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
于 2012-12-15T23:36:01.233 回答