0

I have this code which should work fine

Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Auswertung")
...
ws.Range(Cells(2, 2), Cells(lastRow, lastCol)).NumberFormat = "0"

It however fails if the sheet is not selected. Error 1004, Methode Range fails for the object.

If I change it to

ws.Select
ws.Range(Cells(2, 2), Cells(lastRow, lastCol)).NumberFormat = "0"

it works.

why? In VBA I want to avoid select.

braX
  • 11,506
  • 5
  • 20
  • 33
Matthias Pospiech
  • 3,130
  • 18
  • 55
  • 76

1 Answers1

5

you need to qualify Cells too... The Cells reference does not automatically assume it's referencing the same sheet as your ws.Range like you are expecting. It's using the assumed ActiveSheet unlike your Range object.

Option 1:

ws.Range(ws.Cells(2, 2), ws.Cells(lastRow, lastCol)).NumberFormat = "0"

Option 2:

With ws
  .Range(.Cells(2, 2), .Cells(lastRow, lastCol)).NumberFormat = "0"
End With
braX
  • 11,506
  • 5
  • 20
  • 33