VBA Excel将公式范围从一个工作表复制到另一个工作表

时间:2016-03-03 23:18:43

标签: excel vba excel-vba

我正在尝试将公式从一个工作表复制到另一个工作表。随着“计划”范围的内容发生变化,它们将被复制到“Data_Design”工作表上的不同范围。我的代码间歇性地工作,但我不能确定为什么它不稳定和可重复。我尝试了几种不同的代码变体,但无济于事。当我得到运行时错误(1004)时,它位于等于范围的第一行代码。知道为什么1004?

Sub Design_Save()
Dim A, i, D, Ans As Integer

Redo:
D = Application.InputBox("Enter Design Number" & vbNewLine & vbNewLine & "Note: Default value = current stage number", "Design Number Assignment", Worksheets("Job").Cells(10, 3).Value, Type:=1)

    For i = 2 To 101    ' Revise the 500 to include all of your values
       A = Worksheets("Data_Design").Cells(i, 1).Value
       If A = D Then
            Ans = MsgBox("Design Number " & D & " already exists." & vbNewLine & vbNewLine & "Overwrite exiting design?", vbYesNo + vbQuestion, "Overwrite Design")
            If Ans = vbYes Then
                Save_Design (D)
            Else
                GoTo Redo
            End If
       Else
            Exit Sub
       End If
    Next i
End Sub

Sub Save_Design(A As Integer)
Dim r1, r2 As Integer
Dim dd1, dd2, dd3, dd4, dd101, dd102, dd103, dd104 As Range

If A = 0 Then
  r1 = 1
  Else
    r1 = A * 100
End If
r2 = r1 + 49

Worksheets("Data_Design").Range(Cells(r1, 2), Cells(r2, 6)).Formula = Worksheets("Schedule").Range("C5:G54").Formula
Worksheets("Data_Design").Range(Cells(r1, 7), Cells(r2, 8)).Formula = Worksheets("Schedule").Range("I5:J54").Formula
Worksheets("Data_Design").Range(Cells(r1, 9), Cells(r2, 23)).Formula = Worksheets("Schedule").Range("L5:Z54").Formula
Worksheets("Data_Design").Range(Cells(r1, 24), Cells(r1, 38)).Formula = Worksheets("Schedule").Range("L3:Z3").Formula

End Sub

1 个答案:

答案 0 :(得分:1)

您需要为Cells()范围对象指定正确的父级。试试这个

With Worksheets("Data_Design")
    .Range(.Cells(r1, 2), .Cells(r2, 6)).Formula = Worksheets("Schedule").Range("C5:G54").Formula
    .Range(.Cells(r1, 7), .Cells(r2, 8)).Formula = Worksheets("Schedule").Range("I5:J54").Formula
    .Range(.Cells(r1, 9), .Cells(r2, 23)).Formula = Worksheets("Schedule").Range("L5:Z54").Formula
    .Range(.Cells(r1, 24), .Cells(r1, 38)).Formula = Worksheets("Schedule").Range("L3:Z3").Formula
End With

使用with块可以将以.开头的任何内容分配给with block parentage。