我正在编写一个带有一些循环的小宏,效果很好,但是现在尝试清理并避免使用.Select和.Activate,但是这样做时,我遇到了“错误1004”
使用。选择工作表以查找数据,然后选择。粘贴回工作表,使其工作正常。
下面是一些代码:
Sub Sæt_ind_i_eksporten()
Dim dagensliste As Worksheet
Dim trailerliste As Worksheet
Dim trailernummer As String
Dim finalrow As Integer
Dim i As Integer
Dim t As Integer
Dim targetcount As Integer
Set trailerliste = ThisWorkbook.Sheets("Data ud (2)")
Set dagensliste = ThisWorkbook.ActiveSheet
Application.ScreenUpdating = False
targetcount = trailerliste.Cells(30, 1).End(xlDown).Row
finalrow = Cells(Rows.Count, 1).End(xlUp).Row
For t = 30 To targetcount
trailernummer = trailerliste.Cells(t, 3).Value
For i = 4 To finalrow
If Cells(i, 3) = trailernummer Then
' Here is where it fails - If I select the sheet manually, it moves on
trailerliste.Range(Cells(t, 1), Cells(t, 13)).Copy
' And here it fails again (logic i know!) select manually again and it moves on.
dagensliste.Range(Cells(i, 1), Cells(i, 13)).PasteSpecial xlPasteValues
End If
Next i
Next t
Application.GoTo reportsheet.Range(A1)
MsgBox ("Søgning gennemført")
Application.ScreenUpdating = True
End Sub
如果我在单独的行上将trailerliste.Range(Cells(t, 1), Cells(t, 13)).Copy
和trailerliste.select
分别替换为Range(Cells(t, 1), Cells(t, 13)).Copy
和dagensliste.Select
,而对于PackingDate: new Date().toISOString().slice(0, 19).replace('T', ' ')
则相同,则代码可以正常工作。
我知道这很简单,但是我尝试阅读在论坛上找不到的所有内容。
我希望有人可以帮助我:)
亲切的问候
答案 0 :(得分:4)
Range(Cells(x,y))很棘手,因为您必须指定工作表所在的工作表。
trailerliste.Range(Cells(t, 1), Cells(t, 13)).Copy
必须是
trailerliste.Range(trailerliste.Cells(t, 1), trailerliste.Cells(t, 13)).Copy
答案 1 :(得分:3)
此行:
trailerliste.Range(Cells(t, 1), Cells(t, 13)).Copy
等效于:
trailerliste.Range(ActiveSheet.Cells(t, 1), ActiveSheet.Cells(t, 13)).Copy
如果trailerListe
恰好是活动工作表,则可以正常工作。如果其他工作表处于活动状态,则将导致错误。
错误地使用Range(Cells, Cells)
是Excel VBA中最常见的错误来源之一。它需要对工作表的三个不同引用,而所有三个都必须引用同一工作表。
这将起作用:
trailerliste.Range(trailerliste.Cells(t, 1), trailerliste.Cells(t, 13)).Copy
,但是使用With块通常更容易:
With trailerliste
.Range(.Cells(t, 1), .Cells(t, 13)).Copy
End With
任何以.
开头的引用都引用With
块中的对象-在这种情况下为trailerliste
。
对Range
的类似dagensliste
调用也需要更改为With
块