0

I have been trying to figure out how to merge two tables from the same workbook into a third one using VBA. Example :

Worksheet1:

From     To     Value
Italy    Japan  1000
France   Japan  500
Canada   Japan  0
France   Italy  700

Worksheet2:

From     To     Value
Italy    Japan  5555
France   Japan  1111
Canada   Japan  777
Canada   France 333

Disired output (worksheet3):

From     To     Value1  Value2
Italy    Japan  1000    5555
France   Japan  500     1111
Canada   Japan  0       777
France   Italy  700
Canada   France         333

I would need a VBA solution since the original tables are about 400 rows long, and I would need to perform the same operation for several workbooks. I would be very grateful for any suggestion regarding this problem !

Edit:

In case it is of interest to anyone, I managed to make a working code. Worksheet1 was a nickname for "List Import" and Worksheet2 is "List Export". In both sheets, I inserted a column (C) that states both countries. I used that new column and the values to build the table in Worksheet3 (now "Combolist").

Sub combolist()
    Dim lastRowImp As Long, lastRowExp As Long, startPaste As Long, endPaste As Long
    Dim ws As Worksheet, Lookup_Range As Range, i As Integer
    Dim lastRow As Long

    lastRowImp = Sheets("List Import").Cells(Rows.Count, 1).End(xlUp).Row
    lastRowExp = Sheets("List Export").Cells(Rows.Count, 1).End(xlUp).Row
    startPaste = lastRowImp + 1
    endPaste = lastRowImp + lastRowExp - 1

    'add a new sheet and headers
    Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = "Combolist"
    Sheets("Combolist").Range("B1") = "Import"
    Sheets("Combolist").Range("C1") = "Export"
    Sheets("Combolist").Range("C1").EntireRow.Font.Bold = True

    'copy flows from import and export list
    Sheets("Combolist").Range("A1:A" & lastRowImp) = Sheets("List Import").Range("C1:C" & lastRowImp).Value
    Sheets("Combolist").Range("A" & startPaste & ":A" & endPaste) = Sheets("List Export").Range("C2:C" & lastRowExp).Value

    'remove duplicates
    lastRow = Sheets("Combolist").Cells(Rows.Count, 1).End(xlUp).Row
    Sheets("Combolist").Range(Cells(1, 1), Cells(lastRow, 1)).RemoveDuplicates Columns:=Array(1), Header:=xlYes

    Set ws = ActiveWorkbook.Sheets("Combolist")
    lastRow = Sheets("Combolist").Cells(Rows.Count, 1).End(xlUp).Row

    'populate Import values
    Set Lookup_Range = Sheets("List Import").Range("C1:D" & lastRowImp)

    With ws
        For i = 2 To lastRow
            On Error Resume Next
                If Application.WorksheetFunction.VLookup(ws.Cells(i, 1), Lookup_Range, 2, False) = "" Then
                ws.Cells(i, 2) = 0
                Else
                ws.Cells(i, 2) = Application.WorksheetFunction.VLookup(ws.Cells(i, 1), Lookup_Range, 2, False)
                End If
        Next i
    End With

    'populate Export values
    Set Lookup_Range = Sheets("List Export").Range("C1:D" & lastRowExp)

    With ws
        For i = 2 To lastRow
            On Error Resume Next
                If Application.WorksheetFunction.VLookup(ws.Cells(i, 1), Lookup_Range, 2, False) = "" Then
                ws.Cells(i, 3) = 0
                Else
                ws.Cells(i, 3) = Application.WorksheetFunction.VLookup(ws.Cells(i, 1), Lookup_Range, 2, False)
                End If
        Next i
    End With

End Sub
5
  • 1
    Where is the code you have already tried and where is the error you are experiencing?
    – braX
    Commented Jan 10, 2018 at 13:48
  • Thank you BraX for your interest. I have not tied anything yet. I have made an efficient vba code to build the lists in worksheet1 and worksheet 2 from ugly tables, but now i'm stuck... If you have an idea, just let me know, and i'll try to make a code with it ! Commented Jan 10, 2018 at 14:09
  • Are you hiring a programmer?
    – user8753746
    Commented Jan 10, 2018 at 14:17
  • To be clear @Annick what they mean is SO is not a 'Please write this code for me' site. While you are asking for advice on where to start, generally SO is for programmers who have code written, but are having a hard time in understanding why it won't work. That said, I provided a non-VBA answer that should get you pointed in the right direction. If you need a VBA solution, you'll need to do your research and learn the fundamentals first. Commented Jan 10, 2018 at 14:26
  • I'm sorry if i have hurt anybody on this forum. I didn't ask anybody to write a code, i was asking for suggestions, ideas or guidelines in order to know where to start. When i said "I need a VBA solution" it did not mean "I need someone else to provide me with a vba code", it just meant that i couln'd use a buch of formulas or any manual steps, that's all. Maybe the word "solution" is not well chosen (English is not my native language). Commented Jan 10, 2018 at 14:47

1 Answer 1

1

While this could be solved with VBA, you're likely to be better off using formulas (unless you must do this very frequently). The VBA solution will require some know-how, and even more if you want to be able to maintain the solution.

An Excel formula would be quite simple. First, create a UniqueID column:

UniqueID        From     To     Value
Italy_Japan     Italy    Japan  1000  
France_Japan    France   Japan  500   
Canada_Japan    Canada   Japan  0     
France_Italy    France   Italy  700
Canada_France   Canada   France     

You would do the same thing for both tables. Next, get all of the unique UniqueID's. For this, you could use Data > Remove Duplicates, just be sure to make a copy before removing duplicates, otherwise you are removing records from your source. Put this list of UniqueID's into a new Table. Keep in mind that all of this will be easier if all of your data is in Table format (you'll see a Table tab in the ribbon when inside of the table range.

If you need to format your data as a table, go to the worksheet, press CTRL+HOME (this goes to the very first cell). If your first cell is in another location, just navigate there instead. If your table is the only data on the worksheet, try using CTRL+SHIFT+END from here to highlight to the last used cell. Otherwise, a combination of CTRL+SHIFT+RIGHT and CTRL+SHIFT+DOWN will get you what you need. Finally, name your table for the love of all that is excel, this one simple habit saves a ton of time. For my example I will assume that you have a Primary and Secondary table.

Our formula in our combined table would then look something like this:

=IfError(Vlookup([UniqueID], Primary, Column(Primary[Value]), False), "")

Or, if your Primary table doesn't start in the first column, use this:

=IfError(Vlookup([UniqueID], Primary, 4, False), "")

The difference here is that the former will change the index as the column is moved, the latter will not, and must be edited if the table is edited.

Do the same thing in your next column for the other table:

=IfError(Vlookup([UniqueID], Secondary, Column(Primary[Value]), False), "")

=IfError(Vlookup([UniqueID], Secondary, 4, False), "")

This will 'merge' the two sets based on the shared UniqueID and will leave blanks if the record doesn't exist. Learning how to do this may be less convenient than the learning how to do it in VBA, but I would strongly dissuade you from trying to learn VBA if you can't use an implementation like this.

To be clear, the reason why the formula approach is ideal in this instance is that the task you are asking for help with is very simple, and you would be better developing your Excel skills since, doing so, will allow you to solve similar tasks much faster in the future. Even a novice could implement this solution within 15 minutes or so, where it would easily take you days to learn a scalable VBA solution.

4
  • Thank you Brandon Barney for your insight. It is true that my place is not here since I am not a programmer, but I have seen many other Stack Overflow user ask novice questions, and get advice. I have to write simple VBA code for Excel or Word every now and then, so I don't do it instinctively. In this case, I was so sure I needed a result table with 4 columns, that i was somehow afraid to do a double vlookup or something like that. I didn't think of creating a UniqueID as you suggested. When you pointed that out to me, it became much easier, and now my code is done and works fine. Commented Jan 10, 2018 at 17:55
  • @Annick I am glad it worked out, and I completely agree that this is a place for beginners. At the same time though, that comes with some caution. Its easy to give you the tools you need to be dangerous. Its difficult to give you the tools you need to be successful as a programmer (at least within the scope of an answer). I highly recommend developing your formula skills as much as possible before tackling VBA, if not purely because, without doing so, everything will be a VBA problem. I am still digging myself out of that hole, and I generally consider myself decent at VBA. Commented Jan 10, 2018 at 18:12
  • So nowadays I am far more likely to look at reasonable formula solutions first, before looking at VBA, despite how easy it can be to use VBA to solve a problem, it doesnt mean we always should. Best of luck in your development though. Learning Vlookups was a game changer for me :). Commented Jan 10, 2018 at 18:12
  • Yes, Vlookup is a powerful formula. I knew i could use it in this case, but I needed to automate this task as much as possible, since I am expected to process similar workbooks regularly, 5 or 6 at a time. Thank you again for your time, Brandon. Commented Jan 10, 2018 at 18:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.