gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 21:06:46 24 4
gpt4 key购买 nike

我有一个 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

最佳答案

使用 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

关于excel - VBA 将 Excel 范围导出到特定目录和文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13896822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com