Doubt in vba ADO and Sql query…
I have 2 sheets Namely adodc1,adodc2 (In one workbook)
In adodc1 has columns “Name”,”Dept” and some times its have “Sect” column
In adodc2 has”Name”,”Dept”,”sect” columns
what I want is when i run Query..Vba needs to check whether adodc1 have the Sect column or not ..if it have union the two sheets has usual else
want to return as empty value ..
The below Code taken from ” “altered as per my needs
What it will do is union name and Dept column from two sheets ..now i want query to check whether adodc1 have the Column “sect” or not ..if it has
union “Sect” as usual else .. union as empty value
Sub connecttoexcel()
Dim cn As Object
Dim rs As Object
Dim strFile As String
Dim strCon As String
Dim strSQL As String
Dim s As String
Dim i As Integer, j As Integer
strFile = ActiveWorkbook.FullName
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile & ";Extended Properties=""Excel 12.0 XML;HDR=Yes;IMEX=1"";"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
'here i want some stuff
strSQL = "Select Name, Dept from [Adodc1$] Union Select Name, Dept from [Adodc2$];"
rs.Open strSQL, cn
Worksheets("Sheet3").Cells(2, 1).CopyFromRecordset rs
Set rs = Nothing
End Sub
I suggest you use the OpenSchema method of the Connection object to discover whether the column exists e.g. something like:
or test each one in a loop using an array etc.
The
NZ()function is not a function of Access SQL, which is what is being used here to access Excel data. Rather, it part of the MS Access object model. In short, unless you are running this from an Access VBA project thenNZ()is not available. But the workaround is trivial e.g.has the same effect as
I’ve read Access MVPs (Allen Browne?) say this is preferable to
Nz()anyhow.