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

Back into an answer in Excel
Use Data, What-If Analysis, Goal Seek to find the correct input cell value to reach a desired result
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,215,432
Messages
6,124,860
Members
449,194
Latest member
HellScout

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