visualnewbie09
New Member
- Joined
- Jul 23, 2014
- Messages
- 16
I need to assign headers to a table according to the file name and location. I have attached the example spreadsheet in the link below. Sheet1 contains the table with the data and Sheet2 assigns the headers to each file and location. The code is skipping headers and I can not figure it out.
https://docs.google.com/file/d/0B6UGR9IkfqkuZnB1TDZQSlR6UWM/edit
https://docs.google.com/file/d/0B6UGR9IkfqkuZnB1TDZQSlR6UWM/edit
Code:
Sub FindHeaders()
Dim sh2 As Worksheet, sh1 As Worksheet, sh2_lrow As Long, sh1_lrow As Long, sh1_lcol As Long
Dim sh1_arr, sh2_arr, i As Long, dic As Object
If IsError(Sheets("Sheet2").Range("A1")) Then
MsgBox "Sheet2is missing", vbCritical, "Sheet2error"
Exit Sub
Else
Set sh2 = Sheets("Sheet2")
If sh2.Range("a1") = "" Then Exit Sub
sh2_lrow = sh2.Cells(Rows.Count, 1).End(xlUp).Row
If sh2_lrow = 1 Then Exit Sub
End If
If IsError(Sheets("Sheet1").Range("A1")) Then
MsgBox "Sheet1 is missing", vbCritical, "Sheet1 error"
Exit Sub
Else
Set sh1 = Sheets("Sheet1")
If sh1.Range("b2") = "" Then Exit Sub
sh1_lcol = sh1.Cells(3, Columns.Count).End(xlToLeft).Column
If sh1_lcol = 1 Then Exit Sub
End If
Set dic = CreateObject("scripting.dictionary")
dic.comparemode = 1
sh2_arr = sh2.Range("a1:b" & sh2_lrow)
For i = 2 To sh2_lrow
If sh2_arr(i, 2) <> "" Then
If Not dic.exists(sh2_arr(i, 1) & sh2_arr(i, 2)) Then dic(sh2_arr(i, 1) & sh2_arr(i, 2)) = sh2_arr(i - 1, 1)
End If
Next
sh1_arr = sh1.Range("a1", sh1.Cells(3, sh1_lcol))
For i = 2 To sh1_lcol Step 2
If dic.exists(sh1_arr(3, i) & sh1_arr(2, i)) Then sh1_arr(1, i) = dic(sh1_arr(3, i) & sh1_arr(2, i))
Next
sh1.Range("a1", sh1.Cells(3, sh1_lcol)) = sh1_arr
End Sub