Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA 1004 Error on Loop execution of Macro

Tags:

excel

vba

Can anybody give me a sense of why I'd be receiving a 1004 error on the following code?

If it's not clear, I'm trying to loop all sheets that are not my named sheet and try to select a particular range and copy and paste it to the compiled "Quant Sheet"

Dim ws As Worksheet
Dim x As Integer 
Dim y As Integer
Dim a As Integer
Dim b As Integer
Set ws = Worksheets("Quant Sheet")
x = 1
y = 3
a = 3
b = 2

Worksheets("Quant Sheet").Activate
For Each ws In ActiveWorkbook.Worksheets
If (ws.Name <> "Quant Sheet") Then

   ws.Range("A3").Select
   Selection.Copy
   Sheets("Quant Sheet").Select
   Cells(y, 1).Select
   ActiveSheet.Paste
   y = y + 1


End If

Next ws
like image 253
Bez Avatar asked May 12 '17 21:05

Bez


People also ask

How do I fix Runtime Error 1004 Application defined or object defined error?

Sometimes you may get this error if you record a macro at the worksheet level. You should create a module and enter the code there. In order to do so, go to VBE (Alt + F11) and right click on the module's icon. Insert a new module and enter your code there.

What is runtime error 1004 in VBA Excel?

This error occurs when you try to open the file which does not exist in the mentioned path. For example, it could move, be renamed, or deleted from the mentioned path. One reason for this is the wrong type of path or file name with the excel extension.


1 Answers

You set WS as Worksheets("Quant Sheet") but then use that same variable ws to use in your loop. That may be causing the issue.

Try this:

Dim ws As Worksheet, mainWS As Worksheet
Dim x As Integer, y As Integer, a As Integer, b As Integer
Set mainWS = Worksheets("Quant Sheet")
x = 1
y = 3
a = 3
b = 2

For Each ws In ActiveWorkbook.Worksheets
If (ws.Name <> "Quant Sheet") Then
   ws.Range("A3").Copy Destination:=mainWS.Cells(y, 1)
   y = y + 1
End If

Next ws

Mainly, you want to avoid using .Select/.Activate to make sure you work more directly with the data.

Edit: FYI you can likely further make this more dynamic by not using something like y=y+1 and instead use offset, or a lastRow variable, but that's personal preference as it'll accomplish the same thing. (I'm also assuming the x, a, and b variables are used elsewhere in your macro...

like image 61
BruceWayne Avatar answered Oct 01 '22 12:10

BruceWayne