Problem Description: When Joining 2 Tables using Excel and ADO (ACE OLEDB 12.0) on alphanumeric Strings, ADO does not distinguish between the Keys "a12a" and "A12a" (it treats them as if they would be the same, i.e. case-insensitive). I, however, have alphanumeric keys in my data. The Join will link the data wrongly!
I built a small example in an Excel Workbook to reproduce the behavior. The Excel Workbook contains 3 Sheets:
- AlphaNum1
- AlphaNum2
- Result
AlphaNum1 Sheet contains the following data
Key Val
a12b 1
A12b 2
a12B 3
A12B 4
e12f 7
E12F 8
1234 9
AlphaNum2 Sheet contains the following data:
Key Val
a12b 1
A12b 2
a12B 3
A12B 4
c12d 5
C12D 6
1234 9
I Use the following VBA code to connect to ADO and join the tables (LEFT JOIN):
Sub AlphaNumTest()
Dim oAdoConnection As New ADODB.Connection
Dim oAdoRecordset As New ADODB.Recordset
Dim sAdoConnectString As String, sPfad As String
Dim sQuery As String
On Error GoTo ExceptionHandling
sPfad = ThisWorkbook.FullName
sAdoConnectString = "Provider=Microsoft.ACE.OLEDB.12.0; Extended Properties='Excel 12.0 Xml;HDR=YES;';Data Source=" & sPfad
oAdoConnection.Open sAdoConnectString
sQuery = "Select a1.[Key], a2.[Val] from [AlphaNum1$] a1 LEFT JOIN [AlphaNum2$] a2 ON a1.[Key] = a2.[Key]"
With oAdoRecordset
.Source = sQuery
.ActiveConnection = oAdoConnection
.Open
End With
Dim writeRange As Range
Dim headerRange As Range
'Set headerRange = ThisWorkbook.Sheets("WriteHere").Range("A1")
Set writeRange = ThisWorkbook.Sheets("Result").Range("A2")
' print the table header from recordset
For i = 0 To oAdoRecordset.Fields.Count - 1
' careful! the recordset is zero-indexed like it should be! Excel table however starts at index one, thus the i+1~
ThisWorkbook.Sheets("Result").Cells(1, i + 1).Value = oAdoRecordset.Fields(i).Name
' set bold
ThisWorkbook.Sheets("Result").Cells(1, i + 1).Font.Bold = True
Next i
' print the data directly from recordset!
writeRange.CopyFromRecordset oAdoRecordset
CleanUp:
On Error Resume Next ' Lazy skip
oAdoRecordset.Close
oAdoConnection.Close
Set oAdoRecordset = Nothing
Set oAdoConnection = Nothing
Exit Sub
ExceptionHandling:
MsgBox "Fehler: " & Err.Description
Resume CleanUp
End Sub
Note that it does not matter if I use an INNER or a LEFT JOIN; the result is wrong eiter way - in this example here I use a LEFT JOIN to demonstrate the behavior.
The Result output is AlphaNum1.Key and AlphaNum2.Val joined by LEFT JOIN.
The Expected Result (I am joining using "=" not LIKE...) is:
Key Val
a12b 1
A12b 2
a12B 3
A12B 4
e12f
E12F
1234 9
But ADO gives me the Actual Result (it treats the Keys case insensitive...):
Key Val
a12b 4
a12b 3
a12b 2
a12b 1
A12b 4
A12b 3
A12b 2
A12b 1
a12B 4
a12B 3
a12B 2
a12B 1
A12B 4
A12B 3
A12B 2
A12B 1
e12f
E12F
1234 9
Any ideas why ADO behaves like this? Any ideas how/if I can change the behavior?