Access VBA中的计数SQL语句

Posted

技术标签:

【中文标题】Access VBA中的计数SQL语句【英文标题】:Count SQL statement in Access VBA 【发布时间】:2015-01-05 17:15:55 【问题描述】:

我正在尝试对满足某些条件的访问表中的记录进行计数,并将总计插入到另一个表中的一条记录中。我正在通过 vba 这样做,并试图在其中创建一个 sql 语句,但由于某种原因,它说当我尝试添加时我有太多的行继续,我真的很困惑为什么。任何帮助将不胜感激。

intYear = InputBox("What year is it currently?", "Year Input")

DoCmd.DeleteObject acTable, "ThisTable"



strCreate = "CREATE TABLE MarketSegmentTotals (" & vbCrLf & _
            "[State Medicaid] TEXT," & vbCrLf & _
            "Commercial TEXT," & vbCrLf & _
            "HIX TEXT," & vbCrLf & _
            "MMP TEXT," & vbCrLf & _
            "[CMS Part D (CY " & intYear & ")] TEXT," & vbCrLf & _
            "[CMS Part D (CY " & (intYear + 1) & ")] TEXT" & vbCrLf & _
            ");"


strCount = "INSERT INTO MarketSegmentTotals([State Medicaid], [Commercial], [HIX], [MMP], [CMS Part D (CY " & intYear & ")], [CMS Part D (CY " & (intYear + 1) & ")] ) " & _
"SELECT A.cnt, B.cnt, C.cnt, D.cnt, E.cnt " & _
"FROM ( " & _
    "SELECT COUNT([FORMULARY ID]) as cnt " & _
    "FROM ImportMetricsIDs " & _
    "WHERE [Market Segment]= 'State Medicaid' " & _
") AS A " & _
", ( " & _
    "SELECT COUNT([FORMULARY ID]) as cnt " & _
    "FROM ImportMetricsIDs " & _
    "WHERE [Market Segment]= 'Commercial' " & _
") as B " & _
", ( " & _
    "SELECT COUNT([FORMULARY ID]) as cnt " & _
    "FROM ImportMetricsIDs " & _
    "WHERE [Market Segment]= 'HIX' " & _
") AS C " & _
", ( " & _
    "SELECT COUNT([FORMULARY ID]) as cnt " & _
    "FROM ImportMetricsIDs " & _
    "WHERE [Market Segment]= 'MMP' " & _
") AS D "

【问题讨论】:

【参考方案1】:

VBA 限制由行继续字符连接的行数。

您可以更改此项以重新定义变量以中断续行数。

strCount = "blahblahblah" & _
  "moreblahblahblah" & _
  "lastblahforabit" 
strCount = strCount & "evenmoreblah" & _
  "toomuchblahblahblah"

或者完全消除续行。

strCount = "blahblahblah"
strCount = strCount & "moreblahblahblah"
strCount = strCount & "lastblahforabit" 
strCount = strCount & "evenmoreblah"
strCount = strCount & "toomuchblahblahblah"

【讨论】:

有趣的事实。这种行为并不完全符合语言规范。 An implementation MAY limit the number of characters in an <extended-line>. 它没有很好的文档记录,但在几个不同的地方有一些参考。 OneTwo。它似乎不是很一致,因为第一个链接表明限制是 ​​25,但问题的代码没有超过这个限制,但仍然错误。

以上是关于Access VBA中的计数SQL语句的主要内容,如果未能解决你的问题,请参考以下文章

Access 2007 使用 VBA/SQL 语句中列表框中的 ID 值

Access VBA 中的运行时 3464。尝试使用 SQL 选择语句打开记录集

如何将表单绑定到 Microsoft Access 中的 SQL 语句

VBA 中的 SQL 语句

在access中用vba如何把SQL语句查询到的一个值赋给变量?

如何使用 VBA 动态 SQL SELECT 语句调用 MS Access 参数查询