Excel宏复制&将多个表格中的值粘贴到单独的文本文件中

时间:2016-06-29 19:55:10

标签: vba macros

我正在尝试构建一个宏来导出多个工作表(带有命名选项卡)来分隔文本文件。原始.xlsm文件内置了公式,因此我尝试将每个命名工作表中的值粘贴到单个文本文件中。下面的脚本有效,但只将主Excel文件保存为.xlsx和活动工作表。

我正在尝试复制/粘贴所有工作表,但我的脚本无效:

Sub SaveSheetsAsTxt()
'
' SaveSheetsAsTxt Macro
'
Dim ws As Worksheet

Application.DisplayAlerts = False

'save as XLSX
    ActiveWorkbook.SaveAs Filename:="V:\tech\dd\FUND_HOLDINGS.xlsx", _
        FileFormat:=xlNormal, Password:="", WriteResPassword:="", _
        ReadOnlyRecommended:=False, CreateBackup:=False

MyPath = ThisWorkbook.Path

For Each ws In ThisWorkbook.Sheets
ActiveSheet.Cells.Copy
ActiveSheet.Cells.PasteSpecial Paste:=xlPasteValues
ActiveSheet.Cells.PasteSpecial Paste:=xlPasteFormats
ActiveWorkbook.SaveAs Filename:="V:\tech\dd" & "\" & ActiveSheet.Name & ".txt", _
FileFormat:=xlText, CreateBackup:=False
ActiveWorkbook.Close SaveChanges:=False

Next ws

End Sub

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

你所拥有的东西有几个问题。

  • 不需要在循环内调用Close语句
  • 从.xlsm保存到.xlsx时,需要更改.xlsx工作簿的FileFormat才能正常工作。它应该是xlOpenXMLWorkbook
  • 正如Scott指出的那样,您应该在迭代时激活您每次尝试保存的工作表。

    Sub SaveSheetsAsTxt()
    
    Dim ws As Worksheet
    Application.DisplayAlerts = False
    
    'save as XLSX
    Worksheets.Copy
    ActiveWorkbook.SaveAs Filename:="V:\tech\dd\FUND_HOLDINGS.xlsx", _
    FileFormat:=xlOpenXMLWorkbook, Password:="", WriteResPassword:="", _
    ReadOnlyRecommended:=False, CreateBackup:=False
    ' Close the newly created xlsx file
    ActiveWorkbook.Close
    
    'loop through the worksheets
    For Each ws In ThisWorkbook.Sheets
        ws.Activate
        ActiveSheet.Cells.Copy
        ActiveSheet.Cells.PasteSpecial Paste:=xlPasteValues
        ActiveSheet.Cells.PasteSpecial Paste:=xlPasteFormats
        ActiveWorkbook.SaveAs Filename:="V:\tech\dd" & "\" & ActiveSheet.Name & ".txt", _
        FileFormat:=xlText, CreateBackup:=False
    Next ws
    
    'Close out the workbook now 
    ActiveWorkbook.Close
    End Sub