问题
I saved multiple outlook msg on a specific folder named "email temp folder" and would to reply on the first msg in the folder.
However there is an error: type mismatch occur in the below lines.
Could you somebody help me on this please?
Sub outlookActivate1()
Dim OutApp As Outlook.Application
Dim OutMail As Outlook.MailItem
Dim fso As New FileSystemObject
Dim objFolder As Object
Dim objFile As Object
Dim FileItemToUse As Outlook.MailItem
Dim i As Long
Set OutApp = CreateObject("Outlook.Application")
strPath = "C:\Users\admin\Desktop\email temp folder" & "\"
strFiles = Dir(strPath & "*.*")
Set objFolder = fso.GetFolder(strPath)
For Each objFile In objFolder.Files
If i = 0 Then
Set FileItemToUse = objFile // error: type mismatch
End If
Next objFile
With FileItemToUse
.ReplyAll
.BCC = ""
.Subject = "Hi"
.HTMLBody = "testing"
.BodyFormat = olFormatHTML
.display
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
回答1:
It means that objFile
is not of type Outlook.MailItem
as you declared on top of your code.
Relying on the fact that your email template will always be the first item in the Files
collection of the folder is not really stable, as the file might change position (probably is already not there, since you get the type mismatch
error - you're probably trying to cast another type into a variable that is supposed to be a Outlook.MailItem
type).
My suggestion is to reference directly to the file object; which means, in your code:
Set objFile = fso.GetFile("C:\...\mytemplate.msg")
and keep on running the code without the need to neither getFolder()
nor looping For Each objFile
in the Files
collection, hoping that your file will be the first one.
However, best way to understand these kind of errors is to run the code in debug mode (press F8
and run line by line) and, by adding some watchers, figuring out what is what at run-time.
回答2:
The Outlook object model doesn't provide any direct methods for opening .msg files on the disk. However, you can use the following workarounds to get the job done:
- The CreateItemFromTemplate method of the Application class which allows to create a new Microsoft Outlook item from an Outlook template (.oft) or just a message file (.msg) and returns the new item. See How To: Create a new Outlook message based on a template for more information.
Use the ShellExecute method to open the file programmatically. Be aware, only one instance of the Outlook Application can be run at the same time. Thus, the message file will be opened in a new inspector window.
Sub CreateFromTemplate() Dim MyItem As Outlook.MailItem Set MyItem = Application.CreateItemFromTemplate("D:\message.msg") MyItem.Display End Sub
来源:https://stackoverflow.com/questions/28645519/vba-select-the-first-file-from-a-specific-folder-and-reply-all