在充满Excel文件的文件夹中循环遍历特定工作表并解压缩为.csv

时间:2018-12-03 07:54:31

标签: vba

我正在尝试将Excel工作表文件夹另存为.csv。但是,我只能保存活动工作表的.csv。是否可以指定我要从中添加这些excel文件文件夹中的哪张纸?

非常感谢您!

我应该在哪里将工作表名称放在代码中,以指定仅应针对该特定工作表进行循环?谢谢!

'Loop through each Excel file in folder
  Do While myFile <> ""
    'Set variable equal to opened workbook
    Set wb = Workbooks.Open(Filename:=myPath & myFile)
    nameWb = myPath & Left(myFile, InStr(1, myFile, ".") - 1) & ".csv"
    ActiveWorkbook.SaveAs Filename:=nameWb, FileFormat:=xlCSV
    ActiveWorkbook.Close savechanges:=False
    'Get next file name
      myFile = Dir
  Loop

2 个答案:

答案 0 :(得分:0)

我在项目中做的大致相同。我将要保存的WS复制到新的WB,然后保存新文件。

    Workbooks(ExportFile).Worksheets(ExportSheet).Copy
ActiveWorkbook.SaveAs "path/" & ExportSheet & ".txt", FileFormat:=xlCSV

据我所知,复制工作表是保存特定工作表的唯一方法。

答案 1 :(得分:0)

这里是如何遍历工作表的方法。基本上,您可能会测试名称是否与您的预定列表匹配。您还可以对命名范围进行错误检查,或使用多种其他方式来标记要使用的工作表。

'define variables
Dim wb As Workbook, WS As Worksheet
      Do While myFile <> ""
        'Set variable equal to opened workbook


        Set wb = Workbooks.Open(Filename:=myPath & myFile)


        'Here's the loop you are looking for I think
        For Each WS In wb.Worksheets

            'OR statements/If statements can be used.
            'Also lookout for name syntax being case-sensative. You might
            'want to include Ucase on both sides to defend against inconsistencies.

            If WS.Name = "LetsDoThisSheet!" Or UCase(WS.Name) = UCase("AndThisone2") Then

                WS.Visible = xlSheetVisible
                WS.Activate
                nameWb = myPath & Left(myFile, InStr(1, myFile, ".") - 1) & ".csv"
                ActiveWorkbook.SaveAs Filename:=nameWb, FileFormat:=xlCSV
                ActiveWorkbook.Close savechanges:=False


            End If

        Next WS


        'Get next file name
          myFile = Dir
      Loop
相关问题