I call from a spreadsheet module a function that does some processing in another sheet and returns an integer. I then want to write that integer in a cell in the sheet from where the function has been called. I receive an error 400, I guess I do not correctly handle the switching between the sheets.
Could you help me with that?
Function lastNonZero(Rng As Range) As Integer
i = 19
Do While ActiveCell.Value = 0
ActiveCell.Offset(0, -1).Activate
i = i - 1
Loop
lastNonZero = i
End Function
Extract from the Sub, located in Sheet A’s module:
For j = startRow To startRow + (nRows - 1)
Worksheets("B").Select
Range("Y" & j).Activate
k = lastNonZero(Worksheets("B").Range("Y" & j))
Worksheets("A").Range("BZ" & j) = k
Next j
Try to replace the
Range("Y" & j)line with:When you call
Range(xxx)in a Sheet’s module, it refers to a range in that sheet, whether it is selected or not. But if the sheet is not selected and you try to select/activate the range, it will return an error because you can’t select a range on a sheet that is not the active sheet.ps: that does not change the fact that on the next line (
k = lastNonZero(Worksheets("B").Range("Y" & j))), the argument is not used in thelastNonZerofunction).