0

我有以下 Visual Basic 脚本,它应该将我的收件箱中的电子邮件移动到特定文件夹,但是当我运行它时,什么也没有发生。我对 VBA 很陌生,所以对为什么有点困惑。有什么突出的吗,或者您对如何找出为什么会发生这种情况('nt)有什么建议?谢谢!

代码:

Sub Move_Emails()
Set myNameSpace = Application.GetNamespace("MAPI")
Set myInbox = myNameSpace.GetDefaultFolder(6)
Set myItems = myInbox.Items
Dim myItem As Outlook.MailItem
Dim MailItem As Object
Dim sn As String

For Each MailItem In myInbox.Items
    sn = MailItem.SenderName
    If sn = "John Doe" Then
        Set myDestFolder = myInbox.Folders("Folder1")
    ElseIf sn = "Jane Smith" Then
        Set myDestFolder = myInbox.Folders("Folder2")
    ElseIf sn = "Bob Jones" Then
        Set myDestFolder = myInbox.Folders("Folder3")
    End If
    Set myItem = myItems.Find("[SenderName] = sn")
    While TypeName(myItem) <> "Nothing"
        myItem.Move myDestFolder
        Set myItem = myItems.FindNext

    Wend
Next
End Sub
4

2 回答 2

1

您需要更改设置myItem variable. 在您的代码sn中是一个变量,如果您将它放在引号内,它不会转换为真实的发件人姓名。所以,而不是这一行:

Set myItem = myItems.Find("[SenderName] = sn")

使用这一行:

Set myItem = myItems.Find("[SenderName]='" & sn & "'")

根据以下评论编辑可能的问题...当您以这种方式检查名称时:

If sn = "John Doe" Then

您检查John Doe包括大写/小写的确切名称。我建议以这种方式更改它:

If Ucase(sn) = "JOHN DOE" Then

以避免名称拼写可能出现的问题。为所有签入执行此操作If statement

编辑第二...我刚刚意识到您使用不正确的循环来移动元素。如果您将一个元素移动到另一个文件夹,那么您在使用For each loop. 因此,我建议在新的完整代码中进行如下所述的更多更改:

Sub Move_Emails_improved()
Dim myNamespace, myInbox, myItems ', myDestFolder- NEW CHANGED MOVED TO SEPARATE LINE BELOW
Set myNamespace = Application.GetNamespace("MAPI")
Set myInbox = myNamespace.GetDefaultFolder(6)   
Set myItems = myInbox.items
Dim myItem As Outlook.MailItem
Dim MailItem As Object
Dim sn As String

'NEW LINE BELOW
Dim myDestFolder As Folder
'here you need different kind of loop
Dim i as integer
For i = myInbox.items.Count To 1 Step -1   'loop goes from last to first element
    sn = myInbox.items(i).SenderName

    'first possible problem
    If Ucase(sn) = "JOHN DOE" Then
        Set myDestFolder = myInbox.folders("Folder1")

    'alternatively you could check name in this way
    ElseIf UCase(sn) Like "*JANE SMITH*" Then
        Set myDestFolder = myInbox.folders("Folder2")
    ElseIf sn = "Bob Jones" Then
        Set myDestFolder = myInbox.folders("Folder3")
    End If
    Set myItem = myItems.Find("[SenderName]='" & sn & "'")

    'here we need to check if folder is not set
    'NEW- THIS LINE IMPROVED
    While TypeName(myItem) <> "Nothing" And And Not myDestFolder Is Nothing
        myItem.Move myDestFolder
        Set myItem = myItems.FindNext
        'NEW LINE BELOW
        i = i - 1

    Wend
    'and set destination folder to nothing to eliminate all problems
    Set myDestFolder = Nothing
Next
End Sub

希望它现在可以工作。

于 2013-07-01T19:57:45.007 回答
-1

你也可以使用这个:

If myitem.Sender Like "*" & sn & "*" Then
    ' your code
于 2015-02-03T17:16:54.077 回答