title: Using for loop variable in a function
body: <p><strong>Question:</strong> Is it possible to use a for loop variable in a function?</p>
  <p>I have the following code:</p>
  <pre><code>For Each hcell In hRng
      '(something irrelevant happens)
      
      For Each tCell In tRng
          If tCell = &quot;Name1&quot; Then
              
              RowNum = tWb.Sheets(&quot;Sheet_&quot; &amp; hcell).Cells(Rows.Count, 2).End(xlUp).Row
              EmpCol = 1 + tWb.Sheets(&quot;Sheet_&quot; &amp; hcell).Cells(1, 1).End(xlToRight).Column
              
              tWb.Sheets(&quot;Sheet_&quot; &amp; hcell).Cells(1, EmpCol) = &quot;Name1&quot;
  
                  For i = 2 To RowNum
                      tWb.Sheets(&quot;Sheet_&quot; &amp; hcell).Cells(i, EmpCol) = Application.IfNa(Application.VLookup(hcell &amp; tWb.Sheets(&quot;Sheet_&quot; &amp; hcell).Cells(i, 2), _
                          sheetDiWs.Range(&quot;A2:I&quot; &amp; sheetDiWs.Cells(Rows.Count, 1).End(xlUp).Row), 3, False), &quot;&quot;)
                  Next i
          
          ElseIf tCell = &quot;Name2&quot; Then
              '(same process as above, but different name, different lookup column)
                  
          ElseIf tCell = &quot;Nam3&quot; Then
              '(same process: different name, different lookup column)
          
          End If
      Next tCell
  Next hCell
  </code></pre>
  <p>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:</p>
  <pre><code>RowNum = tWb.Sheets(&quot;Sheet_&quot; &amp; hcell).Cells(Rows.Count, 2).End(xlUp).Row
  EmpCol = 1 + tWb.Sheets(&quot;Sheet_&quot; &amp; hcell).Cells(1, 1).End(xlToRight).Column
  
  tWb.Sheets(&quot;Sheet_&quot; &amp; hcell).Cells(1, EmpCol) = &quot;Name1&quot;
  
      For i = 2 To RowNum
          tWb.Sheets(&quot;Sheet_&quot; &amp; hcell).Cells(i, EmpCol) = Application.IfNa(Application.VLookup(hcell &amp; tWb.Sheets(&quot;Sheet_&quot; &amp; hcell).Cells(i, 2), _
              sheetDiWs.Range(&quot;A2:I&quot; &amp; sheetDiWs.Cells(Rows.Count, 1).End(xlUp).Row), 3, False), &quot;&quot;)
      Next i
  </code></pre>
  <p>The issue here is that the variable <strong>hcell</strong> value comes from the first FOR LOOP.</p>
  <p>Is there any way I can use the current hcell value in my (public) function?</p>