我正在使用一个涉及许多函数的模块,除了在其中调用的子函数之外,这些函数几乎相同。 (参数相同,循环运行相同。)
此类功能的一个示例如下:
Function Run1(lookupString) As Boolean
For i = 1 To nA
For j = 1 To nB
Checkbox = ThisWorkbook.Sheets(i).Cells(j,1)
If Checkbox = lookupString
RunLocation(Checkbox)
Run1 = True
Exit Function
End If
Next j
Next i
Run1 = False
End Function
除了调用“RunLocation”之外,我还有其他相同的函数,这些函数在其他函数中是不同的。有没有办法在这种形式中只有一个函数,但包含它作为参数调用的子函数?
答案 0 :(得分:4)
尝试这样的事情:
Function Run1(lookupString, procName As String) As Boolean
For i = 1 To nA
For j = 1 To nB
CheckBox = ThisWorkbook.Sheets(i).Cells(j, 1)
If CheckBox = lookupString Then
'RunLocation (CheckBox)
Application.Run "'" & ThisWorkbook.Name & _
"'!Module1." & subName, CheckBox
'Adust "Module1" to whatever is the name of the
' code module with the methods you want to run...
Run1 = True
Exit Function
End If
Next j
Next i
Run1 = False
End Function
编辑:使用Evaluate,以及一种使用UDF直接更新工作表的有趣方法(这通常很难做到......)
'************* a few test methods to call *******************
'just return the value
Function DoIt(c As Range)
DoIt = "Value is " & c.Value
End Function
'change the value
Function DoIt2(c As Range)
c.Value = 33
DoIt2 = "Value is " & c.Value
End Function
'a sub instead of a function
Sub DoIt3(c1 As Range, c2 As Range)
c1.Value = c2.Value
c1.Interior.Color = IIf(c1.Value > 10, vbRed, vbYellow)
End Sub
'******************** end test methods ***********************
Sub Tester()
'A1=22
Debug.Print ActiveSheet.Evaluate("=DoIt(A1)") '>> Value is 22
Debug.Print ActiveSheet.Evaluate("=DoIt2(A1)") '>> Value is 33
ActiveSheet.Evaluate "DoIt3(A1,A2)" '>> Sets A1 to A2
End Sub
'######## run as a UDF, this actually changes the sheet! ##############
' changing value in src updates dest and set interior color
Function Tester2(dest, src)
dest.Parent.Evaluate "DoIt3(" & dest.Address(False, False) & "," _
& src.Address(False, False) & ")"
Tester2 = "Changed sheet!"
End Function