You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Access 2016中VBA子串出现次数统计函数报错问题咨询

问题分析:Access 2016中VBA字符串统计函数报错问题

首先,先还原你使用的函数代码(方便参考):

Function StringCountOccurrences(strText As String, strFind As String, _ 
Optional lngCompare As VbCompareMethod) As Long 
' Counts occurrences of a particular character or characters. 
' If lngCompare argument is omitted, procedure performs binary comparison. 
'Testcases: 
'?StringCountOccurrences("", "") = 0 
'?StringCountOccurrences("", "a") = 0 
'?StringCountOccurrences("aaa", "a") = 3 
'?StringCountOccurrences("aaa", "b") = 0 
'?StringCountOccurrences("aaa", "aa") = 1 
Dim lngPos As Long 
Dim lngTemp As Long 
Dim lngCount As Long 
If Len(strText) = 0 Then Exit Function 
If Len(strFind) = 0 Then Exit Function 
lngPos = 1 
Do 
lngPos = InStr(lngPos, strText, strFind, lngCompare) 
lngTemp = lngPos 
If lngPos > 0 Then 
lngCount = lngCount + 1 
lngPos = lngPos + Len(strFind) 
End If 
Loop Until lngPos = 0 
StringCountOccurrences = lngCount 
End Function 

错误原因:可选枚举参数未指定默认值

你遇到的“可能输入了没有前置值或标识符的逗号”错误,核心原因是函数中可选参数lngCompare的定义缺少默认值。

在VBA语法规范中,虽然可选参数允许放在参数列表末尾,但对于VbCompareMethod这类枚举类型的可选参数,Access 2016的VBA解释器无法自动为其分配默认值。当你省略这个参数调用函数时,解释器会误认为你在参数列表中多写了一个无对应值的逗号,从而抛出这个错误。

而函数注释里明确提到“如果省略lngCompare参数,执行二进制比较”,说明原本的设计意图是默认使用vbBinaryCompare,但代码里没有明确实现这一点。

修正方法:为可选参数添加默认值

只需要修改函数的参数定义,给lngCompare加上默认值即可解决问题:

Function StringCountOccurrences(strText As String, strFind As String, _ 
Optional lngCompare As VbCompareMethod = vbBinaryCompare) As Long 

这样修改后,当你省略第三个参数调用函数时,VBA会自动使用vbBinaryCompare作为默认的比较方法,既符合注释描述的逻辑,也能彻底避免报错。

内容的提问来源于stack exchange,提问作者sky3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:29:35