使用Msgbox的VBA运行时错误13

时间:2016-09-06 15:49:53

标签: vba excel-vba runtime-error msgbox excel

我对VBA很新,只有基本的知识水平。

我一直在尝试创建一个宏来将一张纸上的数据与同一工作簿中的多张其他纸张进行交叉引用。如果找到记录,我希望msgbox出现以提醒用户数据的位置。

经过几个小时的搜索互联网并拼凑出一些代码,这就是我所拥有的

Sub search()
Dim ws As Worksheet, found As Range
Dim TextToFind(1 To 20) As String
Dim iText As Long

TextToFind(1) = "Jade Smith"
TextToFind(2) = "Bob Collins"
TextToFind(3) = "Jemima Smythe"

For Each ws In ThisWorkbook.Worksheets
    With ws
        If .Name <> "Blacklisted Candidates" Then 'Do not search blacklist candidates!
            iText = 1
            Do While iText <= UBound(TextToFind)
                If TextToFind(iText) <> "" Then 'Do not search blank strings!
                    Set found = .UsedRange.Find(what:=TextToFind(iText), LookIn:=xlformulas, LookAt:=xlPart, MatchCase:=False)

                    If Not found Is Nothing Then
                        MsgBox "Proxy Candidate Found at " & found.Address
                    Else
                        MsgBox "No Proxy Candidates Found ", vbOKOnly, "Success!"
                    End If
                    iText = iText + 1
                End If
            Loop
        End If
   End With
Next ws

End Sub

但是,此代码未找到其他工作表中的值。

测试时,即使有测试数据,我也会在没有找到数据的情况下获取msgbox。

我有一张大约9张(不断增长)的工作簿,我想在每本工作簿的前9列中搜索指定的数据,如你所见,我已经手动输入宏,但在运行宏时我即使有数据要查找,也不会返回任何结果。

2 个答案:

答案 0 :(得分:4)

您正尝试在两个字符串上使用二元运算符And。您可能打算使用&来连接字符串。

文档:

(这些文档适用于VB.Net,但它们在两种语言中的工作方式相同)

所以要修复它,替换

MsgBox ("Proxy Candidate Found at " And rngX.Address)

通过

MsgBox ("Proxy Candidate Found at " & rngX.Address)

答案 1 :(得分:0)

已修改,以便在内容来自公式

的单元格中进行搜索

两者都总结了评论和litelite答案中已经指出的所有内容,并添加了0.02美分,这里是一个工作代码

Option Explicit

Sub search()
    Dim ws As Worksheet, found As Range
    Dim TextToFind(1 To 20) As String
    Dim iText As Long

    TextToFind(1) = "xxxx"
    TextToFind(2) = "xxxx"
    TextToFind(3) = "xxxxx"

    For Each ws In ThisWorkbook.Worksheets
        With ws
            If .name <> "Blacklisted Candidates" Then 'Do not search blacklist candidates!
                iText = 1
                Do While iText <= UBound(TextToFind)
                    If TextToFind(iText) <> "" Then 'Do not search blank strings!
                        Set found = .UsedRange.Find(what:=TextToFind(iText), LookIn:=xlFormulas, LookAt:=xlPart, MatchCase:=False)

                        If Not found Is Nothing Then
                            MsgBox "Proxy Candidate Found at " & found.Address
                        Else
                            MsgBox "No Proxy Candidates Found ", vbOKOnly, "Success!"
                        End If
                        iText = iText + 1
                    End If
                Loop
            End If
       End With
    Next ws
End Sub