vba - 为什么我的 RecordCount 不应该是 0?

标签 vba excel ms-access

我正在尝试从 Access 数据库中进行的查询中获取结果。但是,当我在excel中查询数据库时,查询没有返回值。为什么是这样?当我尝试(从 Excel)查询普通表或其他查询时,值按预期返回。

我的代码:

Sub sqlCode()
    Dim cnn As New ADODB.Connection
    Dim rst As New ADODB.Recordset
    Dim StrDBPath As String
    Dim strSQL As String

    strSQL = "SELECT * FROM qryHeadsA_ExcelOutput"

    StrDBPath = Application.ActiveWorkbook.Path & "\Daily Closing Report V997.accdb"

    cnn.Open "Provider=Microsoft.Ace.OLEDB.12.0;" & _
                             "Data Source=" & StrDBPath & ";" & _
                             "Jet OLEDB:Engine Type=5;" & _
                             "Persist Security Info=False;"

    rst.Open strSQL, cnn, adOpenStatic, adLockOptimistic

    CopyText (strSQL)

    MsgBox rst.RecordCount

    rst.Close
    cnn.Close
    Set rst = Nothing
    Set cnn = Nothing
End Sub

查询中的 SQL:

SELECT [Heads A].[Date Entered], [Heads A Issues].Department, [Heads A Issues].Equipment, [Heads A Issues].[Operation Issues], Sum([Heads A Issues].Downtime) AS SumOfDowntime1, IIf([Head A Crew]='3','C-Crew',IIf([Head A Crew]='2','B-Crew','A-Crew')) AS Crew
FROM [Heads A] INNER JOIN [Heads A Issues] ON [Heads A].[HeadLineA ID] = [Heads A Issues].[HeadLineA ID]
GROUP BY [Heads A].[Date Entered], [Heads A Issues].Department, [Heads A Issues].Equipment, [Heads A Issues].[Operation Issues], IIf([Head A Crew]='3','C-Crew',IIf([Head A Crew]='2','B-Crew','A-Crew'))
HAVING ((([Heads A Issues].Department)='9240A-F') And ((IIf([Head A Crew]='3','C-Crew',IIf([Head A Crew]='2','B-Crew','A-Crew'))) Like IIf('ALL'='all','*-Crew','ALL')))
ORDER BY [Heads A Issues].Department, [Heads A Issues].Equipment;

同样,在 Access DB 中,此查询提供了超过 10k 条符合此条件的记录。 Access 中是否有选项会限制我的 Excel 文件可以查询的内容?

最佳答案

HAVING条款包含此条件...

Like IIf('ALL'='all','*-Crew','ALL')

但是,您正在使用 ADO 中的查询,这需要不同的通配符: %而不是* 。所以你可以将它更改为 ADO 的这个...

Like IIf('ALL'='all','%-Crew','ALL')

但这意味着您需要同一基本查询的 2 个版本:一个用于在 Access 中设计和测试;另一个用于在 Access 中进行设计和测试。另一个与 ADO 一起使用。如果您希望一个查询在两种情况下执行相同的操作,请使用 ALike%通配符代替 Like ...

ALike IIf('ALL'='all','%-Crew','ALL')

虽然查询应该在两种情况下返回相同的结果,但我不确定 IIf 的逻辑。表达。由于 Access SQL 中的文本比较不区分大小写,'ALL'='all'将始终为 True ...这意味着条件相当于 ALike '%-Crew' 。换句话说,该表达式永远不会给出相当于 ALike 'ALL' 的条件。

关于vba - 为什么我的 RecordCount 不应该是 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31454149/

相关文章:

vba - excel Format(date, "yyyymmdd") 导致编译错误

excel - 在 Excel 中分隔街道名称和后缀的 VBA 或公式?

vba - VBA 可以跨 Excel 实例吗?

ms-access - 如何在 Access 2010 中使用 .mdw 文件

vba - 在 Word 中自动将 .doc 转换为 .htm

excel - 相同的代码不适用于新参数

sql - 如何在 Microsoft Access 中注释掉 SQL 代码?

SQL:如何显示仅30天的记录

vba - 计数记录/行

excel - 如何从工作表中的所有单元格中删除特殊字符