首页 > 解决方案 > 复制一堆工作表并使用原始工作表的范围保存?

问题描述

我想在我的工作簿中复制此工作表并使用原始工作表的 sheet1 的单元格 C29 中的值将其保存为 CSV:Del Mar_Replines_20200831_Macro Build.xlsm。当我运行它时,我得到一个“下标超出范围”错误。

如果我只是将单元格 C29 中的值粘贴为文件名,则宏可以工作。单元格 C29 是一个方程式(不确定这是否会有所不同)。

Sheets("Balance Sheet").Copy
    
    ActiveWorkbook.SaveAs Filename:=Workbooks("Del Mar_Replines_20200831_Macro Build").Worksheets("Sheet1").Range("C29").Value
  
    ActiveWindow.Close

标签: excelvba

解决方案


此宏假定两个工作表位于Workbooks("Del Mar_Replines_20200831_Macro Build")并且您的宏位于同一个工作簿中。

首先:您需要确保 in 中的值C29不包含任何不能在文件名中的非法字符。

With ThisWorkbook 'refers to the workbook that contains your macro
    .Sheets("Balance Sheet").Copy 'the sheet you want to copy

    'When you copy a sheet it becomes active. If you don't identify the save path, 
    'the active workbook will be saved to Excels default save location. 
    'The new saved workbook will be located in Excels default save location;
    'the file name will be the value from "ThisWorkbook.Sheets("Sheet1").(C29)",
    'with file extension ".CSV", and file format "6"(csv). 

    ActiveWorkbook.SaveAs .Sheets("Sheet1").Range("C29").Value & ".csv", FileFormat:=6

    ActiveWindow.Close SaveChanges:=False 'close the new workbook with no popup
End With

推荐阅读