Advertisement
Felix_Demi

Excel Left join VBA code

Mar 23rd, 2024
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VBScript 2.10 KB | Source Code | 0 0
  1. Sub MergeData()
  2.     Dim wbDatabase As Workbook, wbInput As Workbook, wbMerged As Workbook
  3.     Dim wsDatabase As Worksheet, wsInput As Worksheet, wsMerged As Worksheet
  4.     Dim outputRow As Long, i As Long, j As Long
  5.     Dim matchFound As Boolean
  6.    
  7.     ' Open the database and input workbooks
  8.    Set wbDatabase = Workbooks.Open("C:\path\to\database.xlsx")
  9.     Set wbInput = Workbooks.Open("C:\path\to\input.xlsx")
  10.     Set wbMerged = Workbooks.Add
  11.    
  12.     ' Access the relevant sheets
  13.    Set wsDatabase = wbDatabase.Sheets("Foglio1")
  14.     Set wsInput = wbInput.Sheets("AssetOverview")
  15.     Set wsMerged = wbMerged.Sheets(1)
  16.  
  17.     ' Copy header from the input file to the merged file
  18.    wsInput.Rows(1).Copy Destination:=wsMerged.Rows(1)
  19.    
  20.     ' Initialize the starting row for the output data
  21.    outputRow = 2
  22.    
  23.     ' Loop through each row in the input worksheet
  24.    For i = 2 To wsInput.Cells(wsInput.Rows.Count, "B").End(xlUp).Row
  25.         matchFound = False
  26.        
  27.         ' Search for a match in Table1 (columns B and K)
  28.        For j = 2 To wsDatabase.Cells(wsDatabase.Rows.Count, "B").End(xlUp).Row ' Adjust if the actual table range is known
  29.            If wsInput.Cells(i, "B").Value = wsDatabase.Cells(j, "B").Value Or wsInput.Cells(i, "B").Value = wsDatabase.Cells(j, "K").Value Then
  30.                 ' Copy the entire row from input to the merged file
  31.                wsInput.Rows(i).Copy Destination:=wsMerged.Rows(outputRow)
  32.                
  33.                 ' Append additional data from the database file (if needed)
  34.                wsMerged.Cells(outputRow, "Z").Value = wsDatabase.Cells(j, "F").Value ' Example: copying "Genre"
  35.                
  36.                 outputRow = outputRow + 1
  37.                 matchFound = True
  38.                 Exit For
  39.             End If
  40.         Next j
  41.        
  42.         ' Repeat the process for Table2 if needed
  43.    Next i
  44.  
  45.     ' Save the merged workbook
  46.    wbMerged.SaveAs "C:\path\to\final-merged-file.xlsx"
  47.  
  48.     ' Cleanup
  49.    wbDatabase.Close SaveChanges:=False
  50.     wbInput.Close SaveChanges:=False
  51.     wbMerged.Close SaveChanges:=True
  52. End Sub
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement