gpt4 book ai didi

vba - 解析 excel 工作簿并将特定选项卡保存为 .csv 文件

转载 作者:行者123 更新时间:2023-12-04 20:41:25 28 4
gpt4 key购买 nike

我需要帮助将 excel 工作簿中的特定选项卡保存为 1) csv 文件和 2) 以它们所源自的文件命名的文件。

到目前为止,我有这个可以从单个工作簿中取出正确的选项卡并将其保存为 .csv 文件。

Sub Sheet_SaveAs()
Dim wb As Workbook
Sheets("SheetName").Copy
Set wb = ActiveWorkbook
With wb
.SaveAs ThisWorkbook.Path & "\SheetName.csv"
'.Close False
End With
End Sub

如何重命名“SheetName”以便文件另存为,例如 Workbook1SheetName、Workbook2SheetName 等?

我想在一个包含很多很多 excel 文件的文件夹中循环这个函数,所以新的 .csv 文件需要唯一的名称。

我在网上找到了这个,它显示了如何使用 VBA 循环, http://www.ozgrid.com/VBA/loop-through.htm .理论上,只要每个 .csv 文件可以有一个唯一的名称,它就应该与我上面的代码一起使用。如果我错了,请纠正我。

谢谢您的帮助。

最佳答案

正如您所发现的,当您复制没有目的地的工作表时,您最终会得到一个由工作表副本填充的新工作簿。新工作簿变为 ActiveWorkbook property在 VBA 环境中。要将工作簿另存为 CSV 文件,您需要检索工作表 .Name property新工作簿中唯一的工作表。

Sub All_Sheet_SaveAs_CSV()
Dim w As Long, wb As Workbook
Dim fp As String, fn As String

On Error GoTo bm_Safe_Exit
'Application.ScreenUpdating = False 'stop screen flashing
Application.DisplayAlerts = False 'stop confirmation alerts

'start with a reference to ThisWorkbook
With ThisWorkbook
fp = .Path
'cycle through each of the worksheets
For w = 1 To Worksheets.Count
With Worksheets(w)
.Copy
'the ActiveWorkbook is now the new workbook populated with a copy of the current worksheet
With ActiveWorkbook
fn = .Worksheets(1).Name
.SaveAs Filename:=fp & Chr(92) & fn, FileFormat:=xlCSV
.Close savechanges:=False '<~~ already saved in line above
End With
End With
Next w
End With

bm_Safe_Exit:
Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub

注意转 .DisplayAlerts将关闭您通常会收到的警告。虽然这对 CSV 文件格式很有帮助,但如果您尝试覆盖文件,它也不会警告您。

Workbook.SaveAs method文件格式参数为 xlCSV将提供正确的文件扩展名。无需将其作为文件名的一部分包含在内。

如果旨在接收导出到 CSV 过程的特定工作表数量有限,则可以循环通过一组工作表名称而不是工作表索引位置。
Sub Specific_Sheets_SaveAs_CSV()
Dim v As Long, vWSs As Variant
Dim fp As String, fn As String

On Error GoTo bm_Safe_Exit
'Application.ScreenUpdating = False 'stop screen flashing
Application.DisplayAlerts = False 'stop confirmation alerts

vWSs = Array("Sheet1", "Sheet3", "Sheet5")

'start with a reference to ThisWorkbook
With ThisWorkbook
fp = .Path
'cycle through each of the worksheets
For v = LBound(vWSs) To UBound(vWSs)
With Worksheets(vWSs(v))
.Copy
'the ActiveWorkbook is now the new workbook populated with a copy of the current worksheet
With ActiveWorkbook
fn = .Worksheets(1).Name
.SaveAs Filename:=fp & Chr(92) & fn, FileFormat:=xlCSV
.Close savechanges:=False '<~~ already saved in line above
End With
End With
Next v
End With

bm_Safe_Exit:
Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub

关于vba - 解析 excel 工作簿并将特定选项卡保存为 .csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32813062/

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