首页 > 解决方案 > VBA cell.value 作为字符串 - 类型不匹配

问题描述

我有一个姓名数据库,我正在尝试对其进行设置,以便我可以搜索名字,然后将其带到具有所述名字的行。我现在使用的代码是:

Option Compare Text

Sub NameFinder()
'Search for name, then produce name and birthday
Sheets("Guests").Activate

Dim s As String, r As Range, found As Integer

Set begin = Range("D2")

s = InputBox("Enter a name to search.")
Set r = Range(begin, begin.End(xlDown))

found = WorksheetFunction.CountIf(r, s)
MsgBox ("There are " & found & " people with the name " & s)


For Each cell In r
    If cell.Value = s Then
    Application.Goto cell.EntireRow, tru
    End If
Next


End Sub

cell.Value 不查找字符串,因此它不断给我一条错误消息。我能做些什么来阻止这种情况?

标签: excelvbatype-mismatch

解决方案


只需过滤您的名称范围


Option Compare Text

Sub NameFinder()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Guests")
Dim s As String, lr As Long
Dim Found As Range

lr = ws.Range("D" & ws.Rows.Count).End(xlUp).Row
s = InputBox("Enter a name to search")

Set Found = ws.Range("D1:D" & lr).Find(s)

If Not Found Is Nothing Then
    'Filter to name
    ws.Range("D1:D" & lr).AutoFilter 1, s
Else
    MsgBox "Name not found"
End If

End Sub

推荐阅读