Okay, no problem. First, I created a new sheet named "consolidated_eg" and also I renamed the sheet "Original format" to "Original" only. Please, do that things.
Sub UsingSQL()
Dim cn As Object 'ADODB.Connection
Dim cnString As String
Dim rs As Object 'ADODB.Recordset
Dim sqlString As String
Set cn = CreateObject("ADODB.Connection")
cnString = "Provider=Microsoft.Jet.OLEDB.4.0;"
cnString = cnString & "Data Source=" & ThisWorkbook.FullName & ";"
cnString = cnString & "Extended Properties=Excel 8.0;"
sqlString = "SELECT "
sqlString = sqlString & " (DEPTID & Team) AS DEPTID2 "
sqlString = sqlString & ", (DEPTID & MOS2) AS PROGRAM_CODE "
sqlString = sqlString & " FROM [Original$]"
cn.ConnectionString = cnString
cn.Open
Set rs = CreateObject("ADODB.Recordset")
rs.Open sqlString, cn, 1, 1
ThisWorkbook.Worksheets("consolidated_eg").Range("A1").CopyFromRecordset rs
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
Take a look at the variable "sqlString". Its content is the SQL Instruction.
What does means the instruction "SELECT (DEPTID & Team) AS DEPTID2, , (DEPTID & MOS2) AS PROGRAM_CODE FROM [Original$]":
1. Concatenate the columns "DEPTID" and "Team" from the worksheet [Original$] and return them giving them an alias "DEPTID2";
2. Next, return the columns "DEPTID" and "MOS2" from the worksheet [Original$] and return them giving them an alias "PROGRAM_CODE";
Pay attention at the comma ",". It separates the columns. If you miss it, you will receive an run-time error;
The column name at the SQL instruction is the same column name at the worksheet "Original" (in your workbook it is "Original format").
So, if you want to add another columns just follow as is in my code:
e.g.
sqlString = "SELECT "
sqlString = sqlString & " (DEPTID & Team) AS DEPTID2 "
sqlString = sqlString & ", (DEPTID & MOS2) AS PROGRAM_CODE "
sqlString = sqlString & ", MOP"
sqlString = sqlString & ", INVOICE_ID"
sqlString = sqlString & " FROM [Original$]"
And finally, the instruction below is copying the result to a new worksheet:
ThisWorkbook.Worksheets("consolidated_eg").Range("A1").CopyFromRecordset rs
In your case, it could be the "consolidated" worksheet.
I recommend you to learn just the basic of SQL instruction. I'm sure that it will help you so much. Give it a try and reply me.
Bookmarks