do you have an idea how to join two tables with the outer join ? Know to do this in SQL, but I need Excel now.
I have a list of all employees in one column I have a
There is indeed such a thing as a left join in Excel if you use ADO.
Go to the VBA editor (Alt-F11) and add a reference (Tools > References) to "Microsoft ActiveX Data Objects 2.8 Library". Create a new normal module (Insert > Module) and add this code:
Option Explicit
Sub get_employees()
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
' This is the Excel 97-2003 connection string. It should also work with
' Excel 2007 onwards worksheets as long as they have less than 65536
' rows
'With cn
' .Provider = "Microsoft.Jet.OLEDB.4.0"
' .ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & _
' "Extended Properties=Excel 8.0;"
' .Open
'End With
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & _
"Extended Properties=""Excel 12.0 Macro;IMEX=1;HDR=YES"";"
.Open
End With
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
rs.Open "SELECT * FROM [Sheet1$] LEFT JOIN [Sheet2$] ON [Sheet1$].[EMPLOYEE] = " & _
"[Sheet2$].[EMPLOYEE]", cn
Dim fld As ADODB.Field
Dim i As Integer
With ThisWorkbook.Worksheets("Sheet3")
.UsedRange.ClearContents
i = 0
For Each fld In rs.Fields
i = i + 1
.Cells(1, i).Value = fld.Name
Next fld
.Cells(2, 1).CopyFromRecordset rs
.UsedRange.Columns.AutoFit
End With
rs.Close
cn.Close
End Sub
Save the workbook and then run the code and you should get a left-joined list on Sheet3. You'll see that the Employee column is duplicated but you can sort that out by amending the SELECT clause appropriately. You'll also have blank cells rather than 0 hours where there is no match
edit: I've left the details of the Excel 97-2003 connection string in the code comments but have changed the code to use the Excel 2007 onwards connection string instead. I've also added code to output the field names and autofit the columns after the recordset has been output