我正在尝试创建“我的第一个”公式函数,但无法使其正常工作。
返回错误。
首先,我将该功能作为标准模块进行了测试,并在调试控制台中呈现了输出以测试结果。一切都很好。
但是我不能让同一个模块用作功能
功能下方:
以这种方式调用=TEST(val;rng)
|产生#value!
Function TEST(val As String, rng As Range) As String
Dim a, b As String
Dim cel, itm, tst, s As Range
Dim row, l, i As Integer
'-----------------------------------------------------
a = ""
b = ""
val = "ROX.RFL.avi.Rmd.ice"
Set rng = Range(Sheets("DGR").Cells(3, 3), Cells(3, 34))
'-----------------------------------------------------
For Each cel In rng.Cells
If InStr(UCase(val), UCase(cel)) Then
a = a & UCase(cel) & ","
row = Sheets("DGR").Cells(Rows.Count, cel.Column).End(xlUp).row
If row <> 3 Then
For Each itm In Range(Sheets("DGR").Cells(4, cel.Column), Cells(row, cel.Column))
b = b & UCase(itm) & ","
Next itm
End If
End If
Next cel
'-----------------------------------------------------
For Each tst In Split(a, ",")
If InStr(b, tst) > 0 Then TEST = tst
Next tst
End Function
在经过测试的功能下面作为模块:(此功能正常工作)
Sub MKDGR()
Dim val, a, b As String
Dim rng, cel, itm, tst, s As Range
Dim row, l, i As Integer
'-----------------------------------------------------
a = ""
b = ""
val = "ROX.RFL.avi.Rmd.ice"
Set rng = Range(Sheets("DGR").Cells(3, 3), Cells(3, 34))
'-----------------------------------------------------
For Each cel In rng.Cells
If InStr(UCase(val), UCase(cel)) Then
a = a & UCase(cel) & ","
row = Sheets("DGR").Cells(Rows.Count, cel.Column).End(xlUp).row
If row <> 3 Then
For Each itm In Range(Sheets("DGR").Cells(4, cel.Column), Cells(row, cel.Column))
b = b & UCase(itm) & ","
Next itm
End If
End If
Next cel
'-----------------------------------------------------
For Each tst In Split(a, ",")
If InStr(b, tst) > 0 Then Debug.Print tst
Next tst
End Sub
答案 0 :(得分:4)
很多事情会或会出问题。让我们一个接一个地解决他们
Val
是VBA中的保留字。避免使用它。使用不是保留字的内容。例如inptS
Variant
Long
而不是Integer
,否则可能会出现溢出错误Erl
获取导致错误的行。获取MZTools Ver 3。它是免费。Activesheet
,而Activesheet
可能不是您认为合适的表。现在让我们将以上所有内容合并到您的代码中。
代码
Option Explicit
Function TEST(inptS As String, rng As Range) As String
Dim a As String, b As String
Dim cel As Range, itm As Range
Dim tst As Variant
Dim row As Long, l As Long, i As Long
'~~> Use error handling
10 On Error GoTo Whoa
'~~> Fully qualify your range objects
20 With Sheets("DGR")
30 For Each cel In rng.Cells
40 If InStr(UCase(inptS), UCase(cel)) Then
50 a = a & UCase(cel) & ","
60 row = .Cells(.Rows.Count, cel.Column).End(xlUp).row
70 If row <> 3 Then
80 For Each itm In .Range(.Cells(4, cel.Column), .Cells(row, cel.Column))
90 b = b & UCase(itm) & ","
100 Next itm
110 End If
120 End If
130 Next cel
140 End With
150 For Each tst In Split(a, ",")
160 If InStr(b, tst) > 0 Then
170 If TEST = "" Then
180 TEST = tst
190 Else
200 TEST = TEST & vbNewLine & tst
210 End If
220 End If
230 Next tst
240 Exit Function
Whoa:
250 TEST = "Unable to calculate value (" & _
Err.Description & _
", Error in line " & Erl & ")"
End Function