Excel VBA查找功能-不适用于公式单元格

时间:2019-06-18 01:31:18

标签: excel vba

无法使FIND使用包含文本的公式单元格并将结果定位在一定范围内的工作表上。

我创建了一个按钮,单击该按钮应查看一个单元格,获取数据,然后使用完全匹配在另一张纸上的一列中搜索结果。

D11包含一个返回vlookup文本结果的公式 当我按下按钮时,我将执行以下操作

Sub Button3_Click()
    Dim strSearch As String
    Dim rng As Range
    Dim rng1 As Range
    Dim ws As Worksheet
    Dim wb As Workbook

    Set wb = Application.ActiveWorkbook
    Set ws = wb.Worksheets("Auspost_Data")

    strSearch = Worksheets("Report_Tool").Range("D11")
    wb.ws.Range("D:D").Select
    Selection.Find(strSearch)

End Sub

我希望发现内容采用文本值并在列范围内找到完全匹配的内容。

2 个答案:

答案 0 :(得分:0)

尝试一下:

Sub Button3_Click()

    Dim strSearch As String
    Dim rng As Range
    Dim rng1 As Range
    Dim ws As Worksheet
    Dim wb As Workbook
    Dim fnd As Range

    Set wb = Application.ActiveWorkbook
    Set ws = wb.Worksheets("Auspost_Data")

    strSearch = Worksheets("Report_Tool").Range("D11")
    Set fnd = ws.Range("D:D").Find(strSearch)

    MsgBox fnd.Address

End Sub

答案 1 :(得分:0)

请尝试这样的事情...

Sub Button3_Click()
    Dim ws As Worksheet, wsCriteria As Worksheet
    Dim strSearch As String
    Dim rng As Range


    If SheetExists("Auspost_Data") Then
        Set ws = Worksheets("Auspost_Data")
    Else
        MsgBox "There is no Sheet called " & ws.Name & " in the ActiveWorkbook.", vbCritical, "Sheet Not Found!"
        Exit Sub
    End If

    If SheetExists("Report_Tool") Then
        strSearch = Worksheets("Report_Tool").Range("D11")
    Else
        MsgBox "There is no Sheet called Report_Tool in the ActiveWorkbook.", vbCritical, "Sheet Not Found!"
        Exit Sub
    End If

    If strSearch = "" Then
        MsgBox "Search string is empty, there is nothing to find.", vbExclamation, "Empty Search String!"
        Exit Sub
    End If

    Set rng = ws.Range("D:D").Find(what:=strSearch, LookIn:=xlValues, lookat:=xlWhole)

    If Not rng Is Nothing Then
        MsgBox "The search string " & strSearch & " is found in the cell " & rng.Address(0, 0) & ".", vbInformation, strSearch & " Found!"
    Else
        MsgBox "The search string " & strSearch & " was not found.", vbExclamation, strSearch & " Found!"
    End If

End Sub


Function SheetExists(shName As String) As Boolean
    Dim sh As Worksheet
    On Error Resume Next
    Set sh = Worksheets(shName)
    On Error GoTo 0
    If Not sh Is Nothing Then SheetExists = True
End Function

要选择找到的范围,请执行以下操作:

用此替换最后的IF语句...

If Not rng Is Nothing Then
    ws.Select
    rng.Select
Else
    MsgBox "The search string " & strSearch & " was not found.", vbExclamation, strSearch & " Found!"
End If

请注意,如果找到了rng,我已经删除了MsgBox,我认为这里不需要,特别是当代码选择找到的rng。