I have function testFunc
that takes Range
as an argument, loops thorugh its cells and edits them. I have sub testSub
that tests two cases: first is when I pass the current workbook's range to testFunc through: 1. variable Range
2. just as an argument testFunct(...Range("A1:A16"))
.
The second case is when I open another workbook and do the same - pass one of its worksheets
range to the testFunc
directly or via variable.
Function testFunc(aCol As Range)
Dim i As Integer
i = 0
For Each cell In aCol
MsgBox (cell.Value)
cell.Value = i
i = i + 1
Next
testFunc = i
End Function
Sub testSub()
Dim origWorkbook As Workbook
Set origWorkbook = ActiveWorkbook
Dim aRange As Range
Set aRange = ThisWorkbook.Sheets("sheet 1").Range("A1:A16")
Dim dataWorkbook As Workbook
Set dataWorkbook = Application.Workbooks.Open("Y:\vba\test_reserves\test_data\0503317-3_FO_001-2582480.XLS")
Dim incomesNamesRange As Range
Set incomesNamesRange = dataWorkbook.Worksheets("sheet 1").Range("A1:A20")
' origWorkbook.Worksheets("sheet 1").Cells(1, 5) = testFunc(dataWorkbook.Sheets("1").Range("A1:A20"))
origWorkbook.Worksheets("Ëèñò2").Cells(1, 50) = testFunc(incomesNamesRange)
' testFunc aRange
'origWorkbook.Worksheets("sheet 1").Cells(1, 5) = testFunc(aRange) '<---good
' origWorkbook.Worksheets("sheet 1").Cells(1, 5) = testFunc(ThisWorkbook.Sheets("sheet 1").Range("A1:A16"))
End Sub
The problem is, as I indicated with comments, when I open a foreign workbook and pass its range through a variable it gives an error variable not defined
For Each cell In aCol`, while all other cases (including passing range variable of the current workbook) work fine.
I need testFunc
to stay a Function
, because it's a simplfied example of some code from bigger program which needs to take a returned value from a function. And I need to store that Range
in a variable too, to minimize time of the execution.
EDIT: As pointed out in the comments, I replaced Cells(1,5)
with origWorkbook.Worksheet("shee t1").Cells(1,5)
and fixed variable name, but the original mistake changed to variable not defined
. I edited the title and body of the question.
Workbook
object does not have aCells
property, soorigWorkbook.Cells(1, 50)
is not valid. You need to specify which worksheet theCells
.refers to. – YowE3K Jul 6 '17 at 7:10Option Explict
at the top all problem would have been resolved – Shai Rado Jul 6 '17 at 7:10Workbook.Cells
will still error.) – YowE3K Jul 6 '17 at 7:11Option Explicit
will show you the cause of the error. Once you see it, it will take less than a second for you to fix it. – YowE3K Jul 6 '17 at 7:20Option Explicit
, you should now define all your variables - e.g.Dim cell As Range
. That is good practice, even though it involves slightly more work. – YowE3K Jul 6 '17 at 7:27