VBA功能未执行

时间:2014-12-17 17:01:54

标签: excel vba

我试图创建一个在给定单元格范围内查找值的函数,但它没有被执行。它应该返回找到值的单元格。

Function searchInRange(where As Range, what As String) As Range
For Each c In where.Cells
 Debug.Print (c.Value)
    If c.Value = what Then
        searchInRange = c
    End If
Next c

End Function

我从子模块调用它,但它没有被执行。如果我去调试调试器只是跳转到下一个语句而不进入函数。我不明白为什么

编辑

正如很多人建议的那样,我发布了调用函数的模块。这是一个按钮点击功能。正确选择了文件和表格。我知道这是因为最后一句话(PE_Sheet.activate)正常工作。问候。

Private Sub CommandButton1_Click()
Dim PE_File As Workbook
Dim PE_Sheet As Worksheet
Dim cell As Range


Set PE_File = Workbooks(getSelectedWorkbook())
Set PE_Sheet = PE_File.Worksheets("Monitored")
Unload UserForm1

searchAlarmFilter PE_Sheet.Range("A:A"), "5184"

PE_Sheet.Activate
End Sub

2 个答案:

答案 0 :(得分:3)

您还需要set范围

Public Function sir(where As Range, what As String) As Range
Dim res As Range: Set res = Nothing
For Each c In where.Cells
    Debug.Print c.Value
    If c.Value = what Then
        Set res = c
        Exit For
    End If
Next
Set sir = res
End Function

答案 1 :(得分:0)

由于NickSlash是正确的,并且功能看起来应该像他指出的那样,这只是问题的一部分。我无法理解jet为什么,但在调用函数之前卸载表单会使解释器不执行该函数。似乎所有依赖于表单的变量都会随表单一起卸载。这对我来说没有多大意义,但它以这种方式工作。

所以调用函数的正确方法是:

Private Sub CommandButton1_Click()
Dim PE_File As Workbook
Dim PE_Sheet As Worksheet
Dim cell As Range


Set PE_File = Workbooks(getSelectedWorkbook())
Set PE_Sheet = PE_File.Worksheets("Monitored")
searchAlarmFilter PE_Sheet.Range("A1:A500"), "5184"
Unload UserForm1



PE_Sheet.Activate
End Sub

有关该函数的正确版本,请参阅NickSlash的答案。