首次尝试编写函数

时间:2014-05-22 02:35:20

标签: function excel-vba vba excel

我试图为了理解而写一个简单的函数,但我没有成功地使范围正确

由于

Function CountFind(ShtName as string, Rng As Range, FindWhat As String)
Dim ws As Worksheet
Dim CountFind As Range
Dim lRow As Long

 Set ws = ThisWorkbook.Sheets(ShtName)
  lRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row

   Set CountFind= Range(Rng & lRow).Find(What:=FindWhat, LookIn:=xlFormulas, _
                 LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext,     MatchCase:= _
                 False, SearchFormat:=False)

End Function

然后使用它

Sub Test()
   If CountFind("mySheet", "K2:K", "Yes").Count > 0 Then MsgBox "Yes"
End Sub

1 个答案:

答案 0 :(得分:2)

用于调用CountFind的第二个参数不是范围,而是字符串。因此,您必须将第二个参数声明为字符串。

该函数返回一些东西。你希望它返回一个范围。因此,您需要将函数声明为范围,而不是在函数中声明范围。

以下在我的测试中有效。

Function CountFind(ShtName As String, Rng As String, FindWhat As String) As Range
Dim ws As Worksheet
' Dim CountFind As Range
Dim lRow As Long

 Set ws = ThisWorkbook.Sheets(ShtName)
  lRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row

   Set CountFind = Range(Rng & lRow).Find(What:=FindWhat, LookIn:=xlFormulas, _
                 LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
                 False, SearchFormat:=False)
End Function