我正试图解决这个问题而不能。
我一直收到错误:“编译错误 - 参数不是可选的”。我提供参数,并将它们设置为可选!
尝试将字符串和数组传递给函数,并计算传递的字符串中数组字符串的出现次数。
代码在该行停止运行:
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
答案 0 :(得分:2)
Id regionemail Body
--------------------------------------------
1 har@gmail.com Amar@gmail.com,Sima@gmail.com.
2 mic@gmail.com Sam@gmail.com, Suzane@gmail.com
是一个VBA函数,它需要一个强制参数 - 因此编译器会生成一条消息,说明&#34;参数不是可选的&#34;如果你不提供这个论点。 (MSDN documentation of Val
)
将VBA函数名称用作变量名称是一个坏主意,因此我建议您不要将Val
用作变量名称 - 使用Val
或VBA没有的任何其他内容已经使用过了。
如果您真的想要使用myVal
(并且您确定您根本不需要访问Val
功能),那么您可以如果您只是声明它,请将其用作变量名称,例如
Val
你的线路也会出现问题
Dim Val As Variant
因为Set countTextInText = cnt
已被声明为countTextInText
,并且Integer
只应在将变量设置为对象的引用时使用。那条线应该是
Set
答案 1 :(得分:0)
对于那些由于问题标题而迟到该问题的人,就像我一样,在使用.Find方法时收到此错误-
在我的情况下,问题是我Set
的变量未在函数顶部Dim
d
Sub MyTest()
Dim tst, rngAll
rngAll = [a1].CurrentRegion
tst = fnFix1Plus1InValues(ByVal rngAll As Range)
End Sub
Public Function fnFix1Plus1InValues(ByVal rngAll As Range) As Boolean
Dim t1, t2, arr, Loc '<=== Needed Loc added here
Set Loc = rngAll.Find(What:="+", LookIn:=xlValues, LookAt:=xlPart, MatchCase:=False)
If Not Loc Is Nothing Then
Do Until Loc Is Nothing
t1 = Loc.Value
If fnContains(t1, "+") Then
'Do my stuff
End If
Set Loc = rngAll.FindNext(Loc)
Loop
End If
End Function 'fnFix1Plus1InValues