Question: Is it possible to use a for loop variable in a function?
I have the following code:
For Each hcell In hRng
'(something irrelevant happens)
For Each tCell In tRng
If tCell = "Name1" Then
RowNum = tWb.Sheets("Sheet_" & hcell).Cells(Rows.Count, 2).End(xlUp).Row
EmpCol = 1 + tWb.Sheets("Sheet_" & hcell).Cells(1, 1).End(xlToRight).Column
tWb.Sheets("Sheet_" & hcell).Cells(1, EmpCol) = "Name1"
For i = 2 To RowNum
tWb.Sheets("Sheet_" & hcell).Cells(i, EmpCol) = Application.IfNa(Application.VLookup(hcell & tWb.Sheets("Sheet_" & hcell).Cells(i, 2), _
sheetDiWs.Range("A2:I" & sheetDiWs.Cells(Rows.Count, 1).End(xlUp).Row), 3, False), "")
Next i
ElseIf tCell = "Name2" Then
'(same process as above, but different name, different lookup column)
ElseIf tCell = "Nam3" Then
'(same process: different name, different lookup column)
End If
Next tCell
Next hCell
This is the part of the code that keeps repeating, and I was thinking of using a function instead of having the same code a bunch of times:
RowNum = tWb.Sheets("Sheet_" & hcell).Cells(Rows.Count, 2).End(xlUp).Row
EmpCol = 1 + tWb.Sheets("Sheet_" & hcell).Cells(1, 1).End(xlToRight).Column
tWb.Sheets("Sheet_" & hcell).Cells(1, EmpCol) = "Name1"
For i = 2 To RowNum
tWb.Sheets("Sheet_" & hcell).Cells(i, EmpCol) = Application.IfNa(Application.VLookup(hcell & tWb.Sheets("Sheet_" & hcell).Cells(i, 2), _
sheetDiWs.Range("A2:I" & sheetDiWs.Cells(Rows.Count, 1).End(xlUp).Row), 3, False), "")
Next i
The issue here is that the variable hcell value comes from the first FOR LOOP.
Is there any way I can use the current hcell value in my (public) function?
question from:https://stackoverflow.com/questions/66060705/using-for-loop-variable-in-a-function