Excel VBA总是运行在可见的工作表上,而不是参考表

我正在写macros将更新工作簿中的特定工作表(摘要)。 它需要插入一行并为其添加值,但无论在运行macros时哪个工作表处于活动状态,都需要始终更新汇总表。 目前它运行在任何一个活动表上。 每次给出范围或单元格引用时,我已经明确尝试命名该表单。 (我相当新的macros,所以logging了一个macros,给我一个起点,因此select和复制冗长的方式)。

Sub PasteValuesSummary() Dim LookupValue As String Dim LookupRange As Range Dim ws As Worksheet Set ws = ThisWorkbook.Sheets("Summary") Set LookupRange = Sheets("Summary").Range("B1:B1000") LookupValue = Sheets("LastUpdate").Range("A1").Value If Not IsError(Application.Match(LookupValue, LookupRange, 0)) Then Sheets("Summary").Select Sheets("Summary").Rows("4:4").Select Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove Sheets("Summary").Range("B4").Select Sheets("Summary").Range("B4") = "=LastUpdate!R[-3]C[-1]" Sheets("Summary").Range("C2:AP2").Select Selection.Copy ActiveWindow.ScrollColumn = 1 Sheets("Summary").Range("C4").Select Sheets("Summary").Paste Application.CutCopyMode = False Selection.Copy Sheets("Summary").Range("B4:AP4").Select Application.CutCopyMode = False Selection.Copy Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False End If End Sub 

试试这个代码。 我把它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