I'm pretty new to VBA and having a hard time understanding why my code keeps returning the same run-time error 1004. Our assignment is to take a workbook with x amount of sheets (for each year our data is providing) that provide all the values of each stock everyday of the year and then print out the name of the ticker, yearly change, percent change, and total volume.
So far the code runs through for the first sheet but when it tries to move onto the next sheet it gives me a run-time error at the line If ws.Cells(row, 1).Value <> ws.Cells(row + 1, 1).Value Then
I looked up different ways to loop through the sheets but I still got the same thing.
Sub testing()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Range("I1").Value = "Ticker"
ws.Range("J1").Value = "Yearly Change"
ws.Range("K1").Value = "Percent Change"
ws.Range("L1").Value = "Total Stock Volume"
Dim ticker As String
Dim yearly_change As Double
yearly_change = 0
Dim opening As Double
Dim closing As Double
Dim row As Double
Dim counter As Double
counter = 2
For row = 2 To Rows.Count
If ws.Cells(row, 1).Value <> ws.Cells(row - 1, 1).Value Then
opening = ws.Cells(row, 3).Value
End If
If ws.Cells(row, 1).Value <> ws.Cells(row + 1, 1).Value Then
ticker = ws.Cells(row, 1).Value
closing = ws.Cells(row, 6).Value
yearly_change = closing - opening
total_stock_volume = total_stock_volume + Cells(row, 7).Value
ws.Range("I" & counter).Value = ticker
ws.Range("J" & counter).Value = yearly_change
ws.Range("K" & counter).Value = yearly_change / opening
ws.Range("K" & counter).NumberFormat = "0.00%"
ws.Range("L" & counter).Value = total_stock_volume
counter = counter + 1
total_stock_volume = 0
Else
total_stock_volume = total_stock_volume + ws.Cells(row, 7).Value
yearly_change = closing - opening
End If
Next row
Next ws
End Sub
I expected the code to run through all the sheets but it only runs the first sheet