繁体   English   中英

如何使用 Excel 宏 VBA 创建一个新文件,其中数字作为初始文件中工作表的值?

[英]How using the Excel macro VBA to create a new file where numbers as values from the sheet in the initial file?

我有 3 张纸 A、B 和 C。 A 具有指向 B 的超链接,A 具有单元格,其中公式从工作表 C 中获取值。 我想创建一个新文件,其中只有 2 张 A 和 B。因此,我认为宏代码应该包含告诉将 A(从初始文件)复制粘贴到 A(在新文件中)的代码。 不幸的是,我是 VBA 的新手,无法弄清楚要使用哪个代码。 你能帮忙吗?

我使用了下面的代码,但是由于公式取决于 C 我得到了错误。

Sub newfile()
    Sheets(Array("A", "B")).Select
    Sheets(Array("A", "B")).Copy


    ActiveWorkbook.SaveAs Filename:="C:XX.xlsx", FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False


End Sub

您需要将工作表 B 的计算值转换为实际值。 我认为用新名称保存当前工作簿,用当前名称重新保存,打开新工作簿,转换值然后删除工作表 C 很容易。 我也包含了一个错误处理程序:

Sub e()
  Dim wb As Workbook ' declare a variable for the workbook
  On Error GoTo ErrHandle ' add an error handling step
  Application.DisplayAlerts = False ' turn off save-over alerts
  ThisWorkbook.SaveAs "NewBook.xlsm" ' save current book with new name
  ThisWorkbook.SaveAs "CurrentWorkBookName.xlsm" ' resave current book to preserve name
  Set wb = Application.Workbooks.Open("NewBook.xlsm") ' open the new book
  wb.Sheets("B").UsedRange.Value = wb.Sheets("B").UsedRange.Value ' convert B calc values to actual values
  wb.Sheets("C").Delete ' delete sheet C
  wb.Close True ' close the new book and save the changes
  ErrHandle:
  If Err.Number <> 0 Then MsgBox Err.Description 'display error if there was one
  Application.DisplayAlerts = True ' turn on alerts again
End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM