首页 > 解决方案 > 试图避免 .Select 或 .Activate 但失败并出现错误 1004

问题描述

我正在编写一个带有一些循环的小宏,效果很好,但现在尝试清理并避免使用 .Select 和 .Activate,但是这样做时,我遇到了“错误 1004”

使用 .Select 让工作表完美运行以查找数据,然后 .Select 回到应该粘贴的工作表。

这里有一些代码:

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)).Copytrailerliste.select和替换Range(Cells(t, 1), Cells(t, 13)).Copy,并且相同,dagensliste.Select那么代码就完美了。

我知道这是一件简单的事情,但我尝试阅读我在论坛上可以找到的所有内容,但没有运气。

我希望有人能帮助我:)

亲切的问候

标签: excelvba

解决方案


Range(Cells(x,y)) 很棘手,因为您必须指定单元格所在的工作表。

trailerliste.Range(Cells(t, 1), Cells(t, 13)).Copy

必须

trailerliste.Range(trailerliste.Cells(t, 1), trailerliste.Cells(t, 13)).Copy

推荐阅读