【问题标题】:Using vba to copy all content from one workbook to a csv file使用 vba 将所有内容从一个工作簿复制到 csv 文件
【发布时间】:2013-07-03 12:03:24
【问题描述】:

我尝试在 excel 中创建一个 vba 脚本,以便将文件夹中所有 xlsx 文件的内容复制到 cvs 文件中。

我用作帮助:http://www.ozgrid.com/VBA/2007-filesearch-alternative.htm

并创建了以下脚本:

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

我想我只是不明白,这就是它不起作用的原因。此代码创建一个空的 csv 文件,并在每次运行脚本时创建一些奇怪的工作簿。

你能帮帮我吗?

【问题讨论】:

    标签: excel vba csv


    【解决方案1】:

    目前您的代码无需先复制表格就保存到一个空文件中。

    将您的代码更改为:

     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
    

    【讨论】:

      【解决方案2】:

      好的,我找到了适合我的解决方案:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-09
        相关资源
        最近更新 更多