在Dsum中格式化字段

时间:2017-03-18 22:21:04

标签: vba ms-access access-vba

在我的项目中,我使用dsum查询表格来比较年份。但我希望将field作为比较的一年。

Public Function GetValue(whatyear) As Long
    GetValue = DSum("Modification", "Accounting Totals", "Format([EntryDate],'yyyy') = " & whatyear & " AND [ModType] like *2*")
End Function

我一直收到这个错误:

Syntax error (missing opeator in query expression
'Format([EntryDate],'yyyy' = 2016 AND [ModType] like *2*"

对于VBA大师而言,这可能很容易。我该怎么办?

2 个答案:

答案 0 :(得分:3)

你需要年度的qoutes,如果[ModType]是文本,你也需要qoutes。另外,像这样处理null值,否则如果找不到任何行,则会抛出另一个错误:

Nz(DSum("Modification", "Accounting Totals", "Format([EntryDate],'yyyy') = '" & whatyear & "' AND [ModType] like '*2*' "), 0)

如果[ModType]是一个数值,那么like运算符将不起作用,你需要使用另一个运算符,如:=,> =,< =,BETWEEN

答案 1 :(得分:2)

  

知道了 - 我必须从函数声明中删除As Long

如果是这样,您可能没有记录,DSum返回Null。抓住那个 - 正如O. Gungor所展示的 - 与Nz一起。并将年份作为数字:

所以:

Public Function GetValue(ByVal whatyear As Integer) As Currency
    GetValue = Nz(DSum("Modification", "Accounting Totals", "Year([EntryDate]) = " & whatyear & " AND [ModType] Like '*2*'"), 0)
End Function
相关问题