I have this function within my code:
Function get_header(ByVal rw As Range) As Scripting.Dictionary
Dim header As New Scripting.Dictionary
Dim used As Range
Set used = Range(rw.Cells(1, 1), rw.Cells(1, rw.Cells(1, rw.Columns.Count).End(xlToLeft).Column))
For Each cl In used.Cells
header.Add cl.Value, cl.Column
Next
Set get_header = header
End Function
What the function does is it takes the table header and creates a dictionary of column names and the respective indexes, so that the order of columns is not important for the rest of the code.
My question is: is it necessary to use a separate variable to store the value throughout the loop, or can I
- edit the returned value ("get_header") whole time instead of only passing the value at the end or
- use the With structure like this:
Function get_header(ByVal rw As Range) As Scripting.Dictionary
Dim used As Range
With rw
Set used = Range(.Cells(1, 1), .Cells(1, .Cells(1, .Columns.Count).End(xlToLeft).Column))
End With
With get_header
For Each cl In used.Cells
.Add cl.Value, cl.Column
Next
End With
End Function
Also, why should I use any of these structures instead of the others? Thanks for any advice, guys.
Set used = Range(rw.Cells(1, 1), ...in a regular code module will error if the sheet withrwis not active. Something likeSet used = rw.Parent.Range(rw.Cells(1, 1), ...would be more robust.