gpt4 book ai didi

sql - 需要 vba-excel 和 Sql 查询帮助

转载 作者:行者123 更新时间:2023-12-02 20:54:31 25 4
gpt4 key购买 nike

vba ADO和Sql查询的疑问...

我有 2 张纸,即 adodc1、adodc2(在一个工作簿中)

在 adodc1 中,有“Name”、“Dept”列,有时还有“Sect”列

在 adodc2 中有“Name”、“Dept”、“sect”列

我想要的是当我运行查询时..Vba需要检查adodc1是否有Sect列..如果它有联合,则两张表通常有其他

想要返回空值..

以下代码取自“”,根据我的需要进行了更改

它将执行的是两张表中的联合名称和部门列..现在我想查询以检查 adodc1 是否具有列“sect”..如果有

像往常一样联合“Sect”,否则..联合作为空值

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

最佳答案

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

我建议您使用OpenSchema Connection 对象的方法来发现列是否存在,例如像这样:

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' ...

或者使用数组等在循环中测试每一个。

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

NZ() 函数不是 Access SQL 的函数,此处使用 Access SQL 来访问 Excel 数据。相反,它是 MS Access 对象模型的一部分。简而言之,除非您从 Access VBA 项目运行它,否则 NZ() 不可用。但解决方法很简单,例如

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

效果与

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

我读过 Access MVP(Allen Browne?)说这无论如何都比 Nz() 更好。

关于sql - 需要 vba-excel 和 Sql 查询帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9595374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com