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

问题描述

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

我使用了以下代码,但是由于公式取决于 CI 有错误。

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


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


End Sub

标签: excelvba

解决方案


您需要将工作表 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

推荐阅读