[英]Using vba to copy all content from one workbook to a csv file
I tried to create a vba script in excel in order to copy the content of ALL xlsx files in a folder into cvs files. 我试图在excel中创建vba脚本,以便将文件夹中所有xlsx文件的内容复制到cvs文件中。
I used as help: http://www.ozgrid.com/VBA/2007-filesearch-alternative.htm 我用作帮助: http : //www.ozgrid.com/VBA/2007-filesearch-alternative.htm
And created the following script: 并创建了以下脚本:
Sub CopySameSheetFrmWbs()
Dim wbOpen As Workbook
Dim wbNew As Workbook
Const strPath As String = "C:\test\"
Dim strExtension As String
'Comment out the 3 lines below to debug
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
On Error Resume Next
ChDir strPath
strExtension = Dir("*.xlsx")
Do While strExtension <> ""
Set wbOpen = Workbooks.Open(strPath & strExtension)
Set wbNew = Workbooks.Add
wbNew.SaveAs Filename:="C:\test\copiedFile", FileFormat:=xlCSV
wbOpen.Sheets(Sheets.Count).Copy
wbNew.Sheets(Sheets.Count).PasteSpecial
strExtension = Dir
Loop
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
On Error GoTo 0
End Sub
I guess I just don't get it and that is why it is not working. 我想我只是不明白,这就是为什么它不起作用。 This code creates an empty csv file and creates some weird workbooks everytime is run the script. 这段代码会在每次运行脚本时创建一个空的csv文件并创建一些奇怪的工作簿。
Can you please help me? 你能帮我么?
Ok, I found a working solution for me: 好的,我找到了一个可行的解决方案:
Sub CopySameSheetFrmWbs()
Dim wbOpen As Workbook
Dim wbNew As Workbook
Const strPath As String = "C:\vba_test\"
Dim strExtension As String
'Comment out the 3 lines below to debug
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
On Error Resume Next
ChDir strPath
strExtension = Dir("*.xlsx")
Do While strExtension <> ""
Set wbOpen = Workbooks.Open(strPath & strExtension)
With wbOpen
.SaveAs (Left(wbOpen.Name, InStr(wbOpen.Name, ".") - 1)), FileFormat:=xlCSV
strExtension = Dir
End With
Loop
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
On Error GoTo 0
End Sub
Currently your code saves to an empty file without copying the Sheets first. 当前,您的代码会保存到一个空文件,而无需先复制表格。
Change your code to this: 将代码更改为此:
Do While strExtension <> ""
Set wbOpen = Workbooks.Open(strPath & strExtension)
Set wbNew = Workbooks.Add
wbOpen.Sheets(Sheets.Count).Copy
wbNew.Sheets(Sheets.Count).PasteSpecial
strExtension = Dir
wbNew.SaveAs Filename:="C:\test\copiedFile", FileFormat:=xlCSV
Loop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.