简体   繁体   中英

Run-time error 1004

I've run across a new VBA problem: some lines of code will only execute if the sheet in question is active, otherwise they generate an error (Run-time error '1004': Application-defined or object-defined error"). I need the code to be able to run in the background.

Perhaps someone with a fresh pair of (VBA-savvy) eyes can find what's wrong with the lines. (I'm posting them together here but they're actually from different macros.)

Dim senaste As Range
Sheets("PA").Range(Cells(senaste.Row, (senaste.Column - 2)), Cells(senaste.Row, senaste.Column)).Copy

Worksheets("GL").Range(Cells(3, 1), Cells(Sheets("GL").UsedRange.Rows.Count, Sheets("GL").UsedRange.Columns.Count)).Delete

Edit: Great answer below! Did the same with a different line and the coordinates went crazy, what happened? (-4 and -9 used to be -1.)

Set pt = Worksheets("PA").PivotTables("A")
pt.DataBodyRange.Range(pt.DataBodyRange.Cells(-4, (pt.DataBodyRange.Cells.Columns.Count - 9)), pt.DataBodyRange.Cells((pt.DataBodyRange.Cells.Rows.Count - 6), (pt.DataBodyRange.Cells.Columns.Count - 7))).Copy

You're not qualifying all the ranges properly - you need to qualify all the Range and Cells calls so that they specify the same sheet:

Dim senaste As Range
Sheets("PA").Range(Sheets("PA").Cells(senaste.Row, (senaste.Column - 2)), Sheets("PA").Cells(senaste.Row, senaste.Column)).Copy

Worksheets("GL").Range(Worksheets("GL").Cells(3, 1), Worksheets("GL").Cells(Sheets("GL").UsedRange.Rows.Count, Sheets("GL").UsedRange.Columns.Count)).Delete

or you can tidy up by using With blocks:

Dim senaste As Range
With Sheets("PA")
    .Range(.Cells(senaste.Row, (senaste.Column - 2)), .Cells(senaste.Row, senaste.Column)).Copy
End With

and similarly:

With Worksheets("GL")
   .Range(.Cells(3, 1), .Cells(.UsedRange.Rows.Count, .UsedRange.Columns.Count)).Delete
End With

Note the dots before all the .Range and .Cells calls.

For your updated part, you want this:

Set pt = Worksheets("PA").PivotTables("A")
With pt.DataBodyRange
    pt.Parent.Range(.Cells(1, .Columns.Count - 3), .Cells(.Rows.Count - 1, .Columns.Count - 1)).Select
End With

Note that the first Range call needs to be qualified with the Worksheet, not the DataBodyRange, otherwise you will get a range offset from where you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM