Excel VBA编译错误 – 参数不可选,

我试图弄清楚这一点,不能。

我不断收到一个错误:“编译错误 – 参数不可选”。 我提供的参数,他们被设置为可选!

尝试将一个string和一个数组传递给一个函数,并计算传递的string中数组string的出现次数。

代码停止在该行上运行:

Public Function countTextInText(Optional text As String, Optional toCountARR As Variant) As Integer 

用“编译错误:参数不是可选的”消息突出显示Val的行:

  For Each Val In toCountARR 

完整代码:

 Private Sub Worksheet_Change(ByVal Target As Range) Dim nameR As Range Dim colR As Range Dim TKRcnt As Integer Dim TKRarr() As Variant TKRarr = Array("TKR", "THR", "Bipolar") Dim ORIFcnt As Integer Dim ORIFarr() As Variant TKRarr = Array("ORIF", "Ilizarov", "PFN") Set nameR = Range("P2:P9") Set colR = Range("B2:B50,G2:G50,L2:L50") For Each namecell In nameR For Each entrycell In colR If entrycell.text = namecell.text Then TKRcnt = countTextInText(entrycell.Offset(0, 2).text, TKRarr) ORIFcnt = countTextInText(entrycell.Offset(0, 2).text, TKRarr) End If Next entrycell MsgBox (namecell.text & " TKR count: " & TKRcnt & " ORIF count: " & ORIFcnt) Next namecell End Sub Public Function countTextInText(Optional text As String, Optional toCountARR As Variant) As Integer Dim cnt As Integer Dim inStrLoc As Integer For Each Val In toCountARR inStrLoc = InStr(1, text, Val) While inStrLoc <> 0 inStrLoc = InStr(inStrLoc, text, Val) cnt = cnt + 1 Wend Next Val Set countTextInText = cnt End Function 

Val是一个VBA函数,它需要一个单一的强制参数 – 因此,如果你不提供这个参数,编译器会生成一个消息,说“参数不是可选的”。 ( Val MSDN文档 )

使用VBA函数名称作为variables名称是一个坏主意,所以我build议您不要使用Val作为variables名称 – 使用myVal或VBA尚未使用的任何其他名称。

如果你真的想要使用Val (并且你确定你不需要访问Val函数),你可以使用它作为variables名,如果你只是声明它,例如

 Dim Val As Variant 

你的线路也会有问题

 Set countTextInText = cnt 

因为countTextInText已被声明为一个Integer ,并且只能在设置一个variables作为对象的引用时使用Set 。 所以这条线应该是

 countTextInText = cnt