使用单元格引用在vba中获取.find的搜索字符串

时间:2018-04-05 10:33:59

标签: excel vba

我正在尝试编写代码来按主题查找邮件并使用它。当我将确切的主题行作为字符串放在myItems.Find中时,它可以正常工作。但是,如果我在excel表中放置完全相同的东西并尝试运行带有单元格引用的代码,则抛出错误(运行时错误' -2147352567)。请帮帮我。     提前谢谢。

Sub SearchMail()
    Dim myOlApp As New Outlook.Application
    Dim myNameSpace As Outlook.Namespace
    Dim sentbox As Outlook.MAPIFolder
    Dim myItems As Outlook.Items
    Dim myItem As Object
    Dim Found As Boolean
    Dim mail As Outlook.MailItem
    Dim ForwardMail As Outlook.MailItem

    Set myNameSpace = myOlApp.GetNamespace("MAPI")
    Set sentbox = myNameSpace.GetDefaultFolder(olFolderSentMail)
    Set myItems = sentbox.Items

    'This Works!!
    'Set mail = myItems.Find("[Subject] = ""Exact Search text""")


    Workbooks("Outlook Mail.xlsm").Sheets("MailingList").Activate
    Sheets("MailingList").Select

    'This doesn't. Why??
    Set mail = myItems.Find("[Subject] = Cells(17,11).Value")

    Set ForwardMail = mail.ReplyAll
    ForwardMail.Display
End Sub

1 个答案:

答案 0 :(得分:1)

当你把它放在引号中时,它就变成了一个字符串。试试这个:

Set mail = myItems.Find("[Subject] = " & Cells(17,11).Value)

虽然我建议你不要只使用Cell。延迟绑定您的工作表然后使用它:

Set mail = myItems.Find("[Subject] = """ & ThisWorkbook.Worksheets("MailingList").Cells(17,11).Value) & """"

这样您就不必选择工作表