Search code examples
vbaexcelexcel-2007

Compare the mapping table and then change with the database headers(row 1)


How do I compare a mapping table (values in different cells) in excel and map the value of that header to my main database.

Main Database: Main Database

Mapping Table: this is the making table to which the headers (tanu, sweet, etc are the file names and the first row is the names in the database

Tanu's Sheet:

enter image description here

It should map the headers(wgt, ht, bmi, etc) of the file (tanu, sweety, Raju) and compare it with main database and replace it with the headers of main database

 The code written so far
 Sub SelectColumn()
 Dim xColIndex As Integer
 Dim xRowIndex As Integer
   xIndex = Application.ActiveCell.Column
    xRowIndex = Application.ActiveSheet.Cells(Rows.Count, 
     xIndex).End(xlUp).Row
     Range(Cells(2, xIndex), Cells(xRowIndex, xIndex)).Select
   End Sub

Can't get through


Solution

  • This code will check your mapping table and replace headers in each of their Sheets for each workbook tanu, sweety and etc, (it will look for the headers in the range A1:Z1000, change this if you need it to be a bigger range):

    Sub foo3()
    Dim Wbook As Workbook
    Dim wSheet As Worksheet
    Dim wb As ThisWorkbook
    Set wb = ThisWorkbook
    Application.DisplayAlerts = False
    LastCol = wb.Sheets("LMal").Cells(1, Columns.Count).End(xlToLeft).Column 'Check how many columns in the Mapping Table
    LastRow = wb.Sheets("LMal").Cells(Rows.Count, "A").End(xlUp).Row 'Check how many rows in the Mapping Table
    For i = 2 To LastCol
        Filename = "C:\Users\tanu\Desktop\" & wb.Sheets("LMal").Cells(1, i) & ".xlsx" ' Get the Sheet name such as tanu, sweety, etc
        Set Wbook = Workbooks.Open(Filename)
            For x = 2 To LastRow ' loop through rows
            Search = wb.Sheets("LMal").Cells(x, i).Value
            On Error Resume Next
                For Each wSheet In Wbook.Worksheets
                    Set strGotIt = wSheet.Cells.Find(What:=Search, After:=wSheet.Cells(1, 1), _
                               LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, _
                               SearchDirection:=xlNext, MatchCase:=True)
                    If strGotIt <> vbNullString Then
                       wSheet.Cells(strGotIt.Row, strGotIt.Column).Value = wb.Sheets("LMal").Cells(x, 1).Value 'replace the value in tanu's sheet
                       On Error GoTo 0
                    End If
    
                Next
               On Error GoTo 0
            Next x
    
    Wbook.Close SaveChanges:=True
    Application.DisplayAlerts = True
    Next i
    End Sub