【问题标题】:How to copy then paste formulas from one workbook to another with VBA如何使用 VBA 将公式从一个工作簿复制然后粘贴到另一个工作簿
【发布时间】:2015-05-12 15:08:41
【问题描述】:

我有一个现有的 VBA 代码,它将 Excel 工作表从我的源工作簿 (Sourcewb) 复制到新的目标工作簿 (Destwb) 中,但只粘贴值。我需要 Destwb 中的特定范围 (D31:E38) 以包含源工作簿中的公式。我找到了这段代码:

Range("A1:I1105").Copy Sheets("Sheet2").Range("B2")

在这个似乎相关但不知道如何修改它以在我的应用程序中工作的网站(另一个问题)上。我添加了一个注释行“'在计算表中插入总公式”,我认为附加代码会去哪里。这是我现有的代码:

Set Sourcewb = ActiveWorkbook

'Copy the sheet to a new workbook
Sheets("Calculation").Copy
Set Destwb = ActiveWorkbook

'Determine the Excel version and file extension/format
With Destwb
    If Val(Application.Version) < 12 Then
        'You use Excel 97-2003
        FileExtStr = ".xls": FileFormatNum = -4143
    Else
        'You use Excel 2007-2013
            FileExtStr = ".xlsx": FileFormatNum = 51
        End If
End With

'Change all cells in the worksheet to values if you want
With Destwb.Sheets(1).UsedRange
    Application.CutCopyMode = False
    ActiveSheet.Unprotect
        .Cells.Copy
        .Cells.PasteSpecial xlPasteValues
        .Cells(1).Select
End With
Application.CutCopyMode = False

'Insert total formulas in Calc sheet

'Save the new workbook and close it
TempFilePath = Sheets("Calculation").Range("L4").Value
TempFileName = Range("L3").Value

With Destwb
    .SaveAs TempFilePath & "\" & TempFileName & FileExtStr, FileFormat:=FileFormatNum
    .Close SaveChanges:=True
End With

MsgBox "You can find the new file in " & TempFilePath

【问题讨论】:

  • 每个Range 对象都有一个名为“公式”的成员。尝试使用那个。您可能需要触摸单个单元格才能使其正常工作。

标签: vba excel


【解决方案1】:

您可以先复制整个内容,就像您正在做的那样,然后用Sourcewb 中单元格中的公式覆盖Destwb D31:E38 中的单元格。假设Sourcewb 中感兴趣的范围是“D31:E38”并且目标范围和源范围大小相同,您可以执行以下操作:

'Copy all cells
'Your code here

'New code
set formulaRngFromSource = Sourcewb.Sheets("Calculation").Range("D31:E38")
set formulaRngToDest = Destwb.Sheets(1).Range("D31:E38")

i = 1
for each range in formulaRngFromSource
     formulaRngToDest(i).Formula = range.Formula
     i = i + 1
next range

【讨论】:

    【解决方案2】:

    你可以试试:ActiveSheet.PasteSpecial Paste:=xlFormulas

    ActiveSheet.Unprotect
    ...
        .Cells.Copy
        .Cells.PasteSpecial xlPasteValues
        .Cells.PasteSpecial xlFormulas
        .Cells(1).Select
    End With
    

    【讨论】:

      猜你喜欢
      • 2017-09-08
      • 2013-10-21
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      相关资源
      最近更新 更多