Excel VBA始终在可见工作表而不是引用工作表上运行

时间:2016-04-08 07:33:24

标签: excel vba excel-vba

我正在编写一个宏,它将更新工作簿中的特定工作表(摘要)。它需要插入一行并为其添加值,但无论在运行宏时哪个工作表都处于活动状态,它都需要始终更新摘要表。目前,它可以在任何活动的纸张上运行。我每次提供范围或单元格引用时都尝试明确命名工作表。 (我对宏非常陌生,因此录制了一个宏来给我一个起点,因此选择和复制的方式很长。)

overflow: hidden

1 个答案:

答案 0 :(得分:2)

试试这段代码。我认为LookupValue应该约会?

Sub PasteValuesSummary()

     Dim LookupValue As Date
     Dim rFound As Range

     Dim LookupRange As Range
     Dim ws As Worksheet

     Set ws = ThisWorkbook.Worksheets("Summary")

     Set LookupRange = ws.Range("B1:B1000")

     LookupValue = ThisWorkbook.Worksheets("LastUpdate").Range("A1").Value

     Set rFound = LookupRange.Find(What:=LookupValue, SearchFormat:=True)
     If Not rFound Is Nothing Then
        With ws 'Search help on 'With' keyword.
            .Rows("4:4").Insert shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
            .Range("B4").FormulaR1C1 = "=LastUpdate!R[-3]C[-1]"
            .Range("C2:AP2").Copy Destination:=.Range("C4")

            'This is just removing the formula and leaving the values.
            .Range("B4:AP4").Copy
            .Range("B4:AP4").PasteSpecial Paste:=xlPasteValues 'No need to add the other arguments - they're default.
        End With
    End If

End Sub