以下是原始代码按预期工作:
Dim ContactsFolder As Folder
Set ContactsFolder = Session.GetDefaultFolder(olFolderContacts)
Dim SearchContactName As String
Set myItem = Outlook.CreateItem(olMailItem)
Dim NewContactEmail As String
Dim NewMail As Outlook.MailItem
Set NewMail = Application.ActiveInspector.currentItem
' Ask user for inputs
SearchContactName = InputBox("What is the name of your contact you want to comment to on Trello?")
Dim Contact As ContactItem
'search contacts'
For Each Contact In ContactsFolder.Items
If Contact.FullName = SearchContactName Then
If Contact.IMAddress = "" Then 'add trello card link'
Contact.IMAddress = InputBox("What is the Trello card e-mail of this contact?")
Contact.Save
myItem.To = Contact.IMAddress
Else
myItem.To = Contact.IMAddress
End If
End If
Next
myItem.Body = NewMail.Body
myItem.Subject = NewMail.Subject
myItem.Display
我的意图是,当它找到一个联系人时,它会看到它是否在IMaddress中有任何内容。如果它确实有一个链接,那么它将进入" To:"电子邮件。如果没有,outlook将提示用户输入链接,保存联系信息并将链接添加到" To:"电子邮件。就像我之前说过的,这段代码适用于Outlook中的任何联系人,有或没有IMaddress。
我遇到的麻烦是没有保存联系信息。以下是我可以复制错误的代码:
Sub LeaveAComment()
Dim ContactsFolder As Folder
Set ContactsFolder = Session.GetDefaultFolder(olFolderContacts)
Dim SearchContactName As String
Set myItem = Outlook.CreateItem(olMailItem)
Dim NewContactEmail As String
Dim NewMail As Outlook.MailItem
Set NewMail = Application.ActiveInspector.currentItem
' Ask user for inputs
SearchContactName = InputBox("What is the name of your contact you want to comment to on Trello?")
Dim Contact As ContactItem
'search contacts'
For Each Contact In ContactsFolder.Items
If Contact.FullName = SearchContactName Then
If Contact.IMAddress = "" Then 'add trello card link'
Contact.IMAddress = InputBox("What is the Trello card e-mail of this contact?")
Contact.Save
myItem.To = Contact.IMAddress
Else
myItem.To = Contact.IMAddress
End If
Else
If MsgBox("Contact does not exist. Would you like to add one?", vbYesNo, "Confirm") = vbYes Then
End
Else
End
End If
End If
Next
myItem.Body = NewMail.Body
myItem.Subject = NewMail.Subject
myItem.Display
这是我添加
的时候Else
If MsgBox("Contact does not exist. Would you like to add one?", vbYesNo, "Confirm") = vbYes Then
End
Else
End
End If
End If
我遇到了问题。现在,当我运行宏时,无论联系人是否已存在,msgbox都会触发。由于某种原因,原始的If Contact.FullName = SearchContactName被Else覆盖,即使不应该触发Else(至少在我的思考过程中)。我试图扭转逻辑并做:
For Each Contact In ContactsFolder.Items
If Contact.FullName <> SearchContactName Then
但这带来了同样的结果。
有什么想法吗?
答案 0 :(得分:0)
您不能在每个循环中放置以下部分代码:
Else
If MsgBox("Contact does not exist. Would you like to add one?", vbYesNo, "Confirm") = vbYes Then
End
Else
End
End If
End If
假设您有100个联系人,并希望找到一个名为“查理”的联系人。上面代码的一部分给出了消息框,说只检查了100个联系人中的1个后联系人不存在。
您必须将消息框放在循环之外。您可以使用布尔值来检查是否找到了“查理”联系人:
Dim contactFound as boolean
For Each Contact In ContactsFolder.Items
If Contact.FullName = SearchContactName Then
contactFound = true
然后就在循环之后:
If contactFound = false then
If MsgBox("Contact does not exist. Would you like to add one?", vbYesNo, "Confirm") = vbYes Then
End
Else
End
End If
End if