Home » excel » Need help in vba-excel and Sql query

Need help in vba-excel and Sql query

Posted by: admin April 23, 2020 Leave a comment

Questions:

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
How to&Answers:

Vba needs to check whether adodc1 have the Sect column or not

I suggest you use the OpenSchema method of the Connection object to discover whether the column exists e.g. something like:

Set rs = cn.OpenSchema(adSchemaColumns, Array(Empty, Empty, "Adodc1$")
rs.Filter = "COLUMN_NAME = 'Sect'"
If rs.RecordCount = 1 Then
   ' Column exists
   ...

when it comes to check for 50 columns it will be more difficult i think …

rs.Filter = "COLUMN_NAME = 'Sect' OR COLUMN_NAME = 'Name' OR COLUMN_NAME = 'Dept' ...

or test each one in a loop using an array etc.

Is it possible to use NZ Function inside of the sql query

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 then NZ() is not available. But the workaround is trivial e.g.

Nz(Dept, '{{NONE}}')

has the same effect as

IIF(Dept IS NULL, '{{NONE}}', Dept)

I’ve read Access MVPs (Allen Browne?) say this is preferable to Nz() anyhow.