For each only works when sheet is selected, why?

most

Board Regular
Joined
Feb 22, 2011
Messages
106
Office Version
  1. 365
  2. 2019
Platform
  1. Windows
  2. Mobile
Why does this code work when the sheet is selected and not when another sheet is selected/active?
VBA Code:
    Dim r As Range
    Dim LastRow_D1 As Integer
    Dim LastColumn_D1 As Integer
    LastRow_D1 = LastRowColumn(Sheets("Data1"), "R")
    LastColumn_D1 = LastRowColumn(Sheets("Data1"), "C")
    For Each r In Sheets("Data1").Range(Cells(LastRow_D1, 1), Sheets("Data1").Cells(LastRow_D1, LastColumn_D1))
      Debug.Print r.Value
    Next
I get "Run-time error '1004': Application-defined or object-defined error."

This also works in the same way...
For Each r In Sheets("Data1").Range(Cells(LastRow_D1, 1), Cells(LastRow_D1, LastColumn_D1))
 

Excel Facts

Why are there 1,048,576 rows in Excel?
The Excel team increased the size of the grid in 2007. There are 2^20 rows and 2^14 columns for a total of 17 billion cells.
Try
VBA Code:
    For Each r In Sheets("Data1").Range(Sheets("Data1").Cells(LastRow_D1, 1), Sheets("Data1").Cells(LastRow_D1, LastColumn_D1))
      Debug.Print r.Value
    Next
 
Upvote 1
Solution
Yes, it works. I see now why it didn't work =)
Thanks!
 
Upvote 0
You're welcome & thanks for the feedback.
 
Upvote 0

Forum statistics

Threads
1,214,988
Messages
6,122,620
Members
449,092
Latest member
amyap

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top