Createobject outlook application ошибка
Our computers were upgraded to Office 2007. The following script fails to work on 2007, but works in 2003.
Look for the comment FAILS HERE
CreateObject("Outlook.Application") returns an error that the ActiveX object cannot be created:
Thanks for your help!!
Navy Firefighting Engineer
Ответы
Can you run this script on one of the systems with Outlook 2007 installed and post the exact message it prompts you with.
Knowing the error codes will help to determine the problem and resolution.
Is this still an open issue? Please advise. If there is no response within a week we will assume it is resolved and will close this post. Thanks
Все ответы
Can you run this script on one of the systems with Outlook 2007 installed and post the exact message it prompts you with.
Knowing the error codes will help to determine the problem and resolution.
Dim NS ' As NameSpace
Dim objOutlook ' As Application
' Dim objInbox As Outlook.MAPIFolder
Dim objFolder ' As Outlook.MAPIFolder
Dim Item ' As Object
Dim objItems ' As Object, MailItem but could be something else
Dim Icount ' Folder loop counter
Set NS = Nothing
set objOutlook = Nothing
strFolderName = "Public Folders/All Public Folders/USN/NAVAIR/ORLO/Functional Mailboxes/ORLO_498 MUSTER"
Const olFolderInbox = 6
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery _
("Select * From Win32_Process Where Name = 'outlook.exe'")
If colItems.Count > 0 Then wscript.echo "Outlook is running", 1
Set objOutlook = CreateObject("Outlook.Application")
Set objNamespace = objOutlook.GetNamespace("MAPI")
objNamespace.Logon "Default Outlook Profile",, False, True
Set objFolder = GetFolder(strFolderName)
wscript.echo "Using Mailbox: " & strFolderName
On Error Resume Next
wscript.echo ("LoadMailBox Messagecount=" & MessageCount), 1
wscript.echo "Loading Muster Mailbox content"
Set Item = objFolder.Items
'Set Item = objFolder.MailItems 'Outlook2007 seems to use MailItems instead of Items
On Error resume next
For Icount = 1 To MessageCount
' MessageCount comes from the count property of the folder in Outlook
wscript.echo "LoadMailBox, Icount = " & Icount & " MessageCount=" & MessageCount
wscript.echo "SentOn = " & Item(Icount).SentOn
'Outlook 2007 is having trouble with the item properties below
'Is it perhaps because the Outlook ObjectModell has changed?
wscript.echo "SenderName = " & Item(Icount).SenderName
if err.number <> 0 then
wscript.echo "Sender Name has a problem, Error Number " & err.number & " " & err.Description
wscript.echo "Subject = " & Item(Icount).Subject
wscript.echo "Body = " & Item(Icount).Body
' ******************* LOADING OF MESSAGES INTO MEMORY IS COMPLETE *****************
' This means all the messages, regardless of date
wscript.echo MessageCount & " Muster Messages found in LoadMailBox, Reading Inbox complete."
Public Function GetFolder(strFolderPath)
' folder path needs to be something like:
' "Public Folders\All Public Folders\Company\Sales"
Dim objApp ' As Outlook.Application
Dim objNS ' As Outlook.NameSpace
Dim colFolders ' As Outlook.Folders
Dim objFolder ' As Outlook.MAPIFolder
Dim arrFolders ' As String array
On Error Goto 0
'On Error Resume Next
if dbg then wscript.echo "GetFolder path = " & strFolderPath, 1
if dbg then wscript.echo "Adjusted folder path = " & strFolderPath
Set objApp = CreateObject("Outlook.Application")
' If Outlook is not installed, the folder will be nothing
If Err.number <> 0 Then
wscript.echo "Function GetFolder, CreateObject Outlook.Application"
On Error Goto 0
Set objNS = objApp.GetNamespace("MAPI")
Set objFolder = objNS.Folders.Item(arrFolders(0))
On Error Resume Next
If Not objFolder Is Nothing Then
For I = 1 To UBound(arrFolders)
Set colFolders = objFolder.Folders
Set objFolder = Nothing
Set objFolder = colFolders.Item(arrFolders(I))
If Err.Number <> 0 then
Msgbox "It appears that you do not have access permissions to the Muster Mailbox, call the Mailbox Owner"
if dbg then wscript.echo "Folder = " &objFolder, 1
If objFolder Is Nothing Then
Set GetFolder = objFolder
'If Dbg Then MsgBox("Getfolder is returning " & GetFolder)
On Error Resume Next
Set colFolders = Nothing
Set objNS = Nothing
Set objApp = Nothing
On Error Goto 0
Outlook is running
Using Mailbox: Public Folders\All Public Folders\USN\NAVAIR\ORLO\Functional Mail
В этой статье описываются известные проблемы, которые могут возникнуть при использовании Microsoft Outlook 2010, русская версия объектной модели.
Невозможно создать Outlook.Application объект из повышенного процесса
Невозможно автоматизировать Outlook с помощью процесса, запущенного с повышенными разрешениями в Windows Vista, в Windows 7 или в любой другой операционной системе, которая позволяет запускать процессы с повышенными разрешениями. Это является одним из ограничений com. И Outlook, и настраиваемые программы, Outlook должны работать на одном уровне целостности.
События BeforeItemMove и BeforeFolderMove не происходят
Существует несколько сценариев, в BeforeItemMove которых BeforeFolderMove события и события не происходят. Известные сценарии включают удаление встреч из To-Do, удаление собраний из календаря и To-Do, реализацию событий в папках ненадеги и удаление элементов с помощью команды Игнорировать беседу. Эти проблемы были устранены в накопительном обновлении за декабрь 2010 г. Outlook 2010 г.
Метод GetProperty сбой в режиме online
Если вы используете Microsoft Exchange 2010 в режиме online и GetProperty используете метод для извлечения свойства из незавербенного элемента, метод может привести к сбой. Это из-за изменения способа обработки свойств 2010 Exchange 2010. Outlook 2007 также затрагивается. Текущие обходные пути включают следующие:
- Используйте Outlook кэшировали в кэшном режиме.
- Перед вызовом метода убедитесь, что элемент находится в сохраненных GetProperty состояниях.
Окно Inspector может закрыться неправильно
Если вы реализуете GetVisibleCallback функцию Microsoft Visual Studio Tools for Microsoft Office (VSTO), пользователь не сможет правильно закрыть окно инспектора. Эта проблема была исправлена в накопительном обновлении за февраль 2011 г. Outlook 2010 г.
Событие BeforeCheckNames происходит в другое время, чем в Outlook 2007 г.
В Outlook 2010 г. событие BeforeCheckNames происходит после решения получателей, а не перед их решением. Это означает, что отмена события не влияет. Эта проблема была исправлена в Outlook 2010 г. Накопительное обновление за февраль 2011 г.
Объектная модель представлений может не соответствовать фактическому представлению в пользовательском интерфейсе
Существуют сценарии, в которых при программном изменении представлений или извлечении параметров представления параметры объектной модели могут не соответствовать фактическим Outlook, отображаемой в пользовательском интерфейсе. Для решения этой проблемы в Outlook за февраль 2011 г. были сделаны улучшения.
Вложения не поддерживаются правильно при использовании окна Insert Item
Не удается вставить вложения элементов с помощью учетной записи POP/IMAP
Если вы используете метод Attachments.Add для добавления Outlook элементов с помощью учетной записи POP/IMAP, вызов не удается. Эта проблема была устранена в накопительном обновлении за декабрь 2010 г. Outlook 2010 г.
MailItem.Recipients.ResolveAll Функция удаляет получателей из поля To
Метод GetAssociatedAppointment не удается для запроса собрания в папке Отправленные элементы
Если вы пытаетесь получить встречу из запроса на собрание в папке Отправленные элементы, вызов не удается. Эта проблема была исправлена в накопительном обновлении за февраль 2011 г. Outlook 2010 г.
Данные о встрече могут не обновляться, если открыто окно инспектора
Из-за внутренних изменений в том, как Outlook 2010 года обработки и кэш-встречи, объектная модель может не предоставлять последние сведения об исключениях для встреч, если соответствующее назначение открыто в окне инспектора. Такое поведение происходит, даже если вы ото всех ссылок и повторно извлекаете элемент из магазина. Чтобы решить эту проблему, убедитесь, что окно встречи закрыто. Изменить такое поведение не планируется.
NavigationFolder.Folder создает ошибку в общей папке
Referring to following coding, under Mail_small_Text_Outlook(), when I try to run this macro, it pops up an error on following line:
>>> Set OutApp = CreateObject("Outlook.Application")
Execution Error ‘-2147024770 (8007007e)
Cannot find module
I am using Window XP with SP3 and Outlook 2003 SP3
Does anyone have any suggestions on how to fix it?
Thanks in advance for any suggestions
Sub Mail_small_Text_Outlook()
'Working in Office 2000-2010
Dim OutApp As Object
Dim OutMail As Object
Dim strbody As String
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
strbody = "Hi there" & vbNewLine & vbNewLine & _
"This is line 1" & vbNewLine & _
"This is line 2" & vbNewLine & _
"This is line 3" & vbNewLine & _
"This is line 4"
On Error Resume Next
With OutMail
.To = *** Email address is removed for privacy ***
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
.Body = strbody
'You can add a file like this
'.Attachments.Add ("C:\test.txt")
.Send 'or use .Display
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
This thread is locked. You can follow the question or vote as helpful, but you cannot reply to this thread.
Report abuse
Harassment is any behavior intended to disturb or upset a person or group of people. Threats include any threat of suicide, violence, or harm to another. Any content of an adult theme or inappropriate to a community web site. Any image, link, or discussion of nudity. Any behavior that is insulting, rude, vulgar, desecrating, or showing disrespect. Any behavior that appears to violate End user license agreements, including providing product keys or links to pirated software. Unsolicited bulk mail or bulk advertising. Any link to or advocacy of virus, spyware, malware, or phishing sites. Any other inappropriate content or behavior as defined by the Terms of Use or Code of Conduct. Any image, link, or discussion related to child pornography, child nudity, or other child abuse or exploitation.
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
I am trying to create an outlook email to send with multiple attachments, but I keep getting a catastrophic error when the VBA code in Microsoft Access gets to the CreateObject("Outlook.Application") line. Why is this happening? What do I need to do to get this to work? I have Microsoft Outlook 15.0 Object Library reference included. Here is my code:
Private Sub cmdDoBulkEmails2_Click()
On Error GoTo Err_cmdDoBulkEmails2_Click
Dim con As ADODB.Connection
Dim objOL As Object
Set objOL = CreateObject("Outlook.Application")
Dim rsMembers As ADODB.Recordset
Dim MembersCriteria As String
Dim strEmail As String
Dim strSubject As String
Dim strIssue As String
Dim strNewsletterBody As String
Dim strSeminarBody As String
Dim strBody As String
Dim strOther As String
Dim strTo As String
Dim strBCC As String
Dim sttBCCList As StreamReadEnum
Dim strItems As String
Dim n As Integer
Dim ctlSource As Control
Dim strItemsAttch As String
Dim intCurrentRowAttch As Integer
Dim RecCount As Long
Dim MemCount As Long
Dim RemainCount As Long
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile As Object
Set oFile = fso.CreateTextFile(Me.txtEmailSentPath)
Set ctlSource = Me.lbAttachment
Set con = Application.CurrentProject.Connection
Set rsMembers = New ADODB.Recordset
rsMembers.CursorType = adOpenKeyset
rsMembers.LockType = adLockOptimistic
MembersCriteria = "Select * from TestMembers"
rsMembers.Open MembersCriteria, con, 1 ' 1 = adOpenKeyset
Set objNS = objOL.GetNameSpace("MAPI")
strSubject = Me.txtSubject
strBody = Me.txtBody
strTo = Me.txtTo
strBCC = ""
strItems = ""
If Not rsMembers.EOF Then
rsMembers.MoveFirst
RecCount = rsMembers.RecordCount
MemCount = 0
Do While Not rsMembers.EOF
Set MyItem = objOL.CreateItem(olMailItem)
Set MyAttachments = MyItem.Attachments
MyItem.TO = strTo
MyItem.Subject = strSubject
MyItem.Body = strBody
For intCurrentRowAttch = 0 To ctlSource.ListCount - 1
If ctlSource.Selected(intCurrentRowAttch) Then
strItems = ctlSource.Column(3, intCurrentRowAttch)
MyAttachments.Add strItems
strItems = ""
End If
Next intCurrentRowAttch
If Not rsMembers.EOF Then
rsMembers.MoveFirst
RecCount = rsMembers.RecordCount
MemCount = 0
Set MyItem = objOL.CreateItem(olMailItem)
Set MyAttachments = MyItem.Attachments
MyItem.TO = strTo
MyItem.Subject = strSubject
MyItem.Body = strBody
For intCurrentRowAttch = 0 To ctlSource.ListCount - 1
If ctlSource.Selected(intCurrentRowAttch) Then
strItems = ctlSource.Column(3, intCurrentRowAttch)
MyAttachments.Add strItems
strItems = ""
End If
Next intCurrentRowAttch
MyItem.TO = strTo
RemainCount = RecCount - MemCount
For n = 1 To IIf(RemainCount > 20, 20, RemainCount)
strEmail = Nz(rsMembers![E-MAIL_ADD], "")
If strEmail <> "" Then
strBCC = strBCC + strEmail + "; "
End If
If Not rsMembers.EOF Then
rsMembers.MoveNext
MemCount = MemCount + 1
End If
Next n
If strBCC <> "" Then
MyItem.BCC = strBCC
oFile.WriteLine strBCC
strBCC = ""
End If
End If
Loop
End If
MsgBox "We are done. Refresh your emails."
rsMembers.Close
Set ctlSource = Nothing
oFile.Close
Set oFile = Nothing
Set fso = Nothing
Set MyAttachments = Nothing
Set MyItem = Nothing
Set objNS = Nothing
Set objOL = Nothing
Set con = Nothing
Exit_cmdDoBulkEmails2_Click:
Exit Sub
'MsgBox Err.Description
MsgBox "Automation Error " & vbCr & Err.Number & _
" (" & Hex(Err.Number) & ")" & Err.Description
' Resume Next
Resume Exit_cmdDoBulkEmails2_Click
Answers
I finally upgraded the laptop to Windows 10 and reinstalled Office 365 which also upgraded to Access to 2016. I ran the code and everything works again. Yeah.
- Proposed as answer by Edward8520 Microsoft contingent staff Monday, November 30, 2015 2:41 AM
- Marked as answer by Edward8520 Microsoft contingent staff Monday, December 7, 2015 8:02 AM
All replies
I suspect that you are wondering why no one has responded to your post. I think I can safely say that you have baffled everyone with what you have going on here. There are a number of problems with your code including major unnecessary redundancies, infinite looping, among many other issues.
I'm not sure if I have a full grip on what you're trying to accomplish. However, I have rewritten your code and I am providing the revised work here for you to test and determine suitability for your requirements.
I hope that this helps you out.
Thank you for rewriting the code. I hadn't considered the fact that I should isolate the creation of the outlook.application to be created for each new email generated. The code works fine. However, I am still getting the Automation Error Catastrophic failure in procedure OutlookSendMessage with error number -2147418113. So, the email is never created. I'm beginning to believe that there is some problem with Outlook's ability to receive the VBA calls to create the emails. What would you suggest I do?
Thanks again for your help!
>> I am still getting the Automation Error Catastrophic failure in procedure OutlookSendMessage with error number -2147418113.
Did you mean you get this error in this line “Set objOutlook = CreateObject("Outlook.Application")”?
I suggest you open you outlook manually to check whether you could send a mail.
If you could not, it would be better if you could share us the errors. If you could, I suggest you try to use early binding. You could refer the link below for more information.
In addition, I suggest you test the simple code below to check whether you still get this error.
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey.
Yes, I get this error in this line “Set objOutlook = CreateObject("Outlook.Application"). Yes, I can manually send an Outlook mail ok. This error is happening on my laptop when is Windows 8.1 with Office 365. When I copy the database to my desktop which is Windows Vista Home Premium and Microsoft Office Professional 2007, I get different error. I must note that my emails seemed be home to my desktop and secondary to my laptop on refresh only.
On desktop for each recipient, I get a prompt to allow email to be generated (my antivirus is current, but for some reason Outlook doesn't think it's active and continues to prompt for each recipient). So I keep allowing the email to be generated. Then when it gets to the line to Set objAttachment = .Attachments.Add(CStr(AttachmentPath). CStr(NZ(AttachmentName, ""))) it errors out because AttachmentPath contains full path and file name for every attachment while AttachmentName is null. So I tried parsing out the path separately from the name for each attachment and one at a time use this line of code to add a single attachment at a time instead of all attachments at once. Still don't have it right. Don't know if this is related to Catastrophic error on my laptop or not. I can send/receive emails on my laptop as well manually.
Any other ideas? or suggestions to fix what is wrong?
Based on your description, did you mean this“Set objOutlook = CreateObject("Outlook.Application")” would not generate error in your pc? If so, I assume your original error might be caused by office broken.
I suggest you repair your Office, and try again. If you still get this error, I would suggest you uninstall/install your Office.
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey.
I think your first problem that you need to overcome is trying to develop your system between different environments and Access versions. Every time you open your file on a different machine with a different environment, Access will try to adjust the references. Unfortunately, it isn't always successful. That will cause certain problems in your code. That brings me to your next problem.
It sounds like you may not have a reference set up appropriately if the code fails on the "Set" line. I get the idea that you may not be compiling your code before you attempt to run it either, because your original code had numerous issues. Check your references and be sure that you're up to date on whatever machine your developing on. Then compile your code to ensure that everything compiles without issue. Make any corrections where necessary. Then walk through your code one line at a time by pressing F8. You can begin by launching your code from your button with a breakpoint set at the first line. Then just walk through until you reach the end. If you encounter an error in between, trace the source of the problem down, correct it, then repeat your walk until you've successfully completed your procedure(s). This is called debugging. We can't do it for you since we don't have your equipment or your application to test.
As for your problem with the Attachments, it should not have anything to do with the file existing in the file path. See the following:
expression . Add (Source, Type, Position, DisplayName)
expression A variable that represents an Attachments object.
Parameters
Variant
The source of the attachment. This can be a file (represented by the full file system path with a file name) or an Outlook item that constitutes the attachment.
Long
The type of the attachment. Can be one of the OlAttachmentType constants.
Long
This parameter applies only to e-mail messages using the Rich Text format: it is the position where the attachment should be placed within the body text of the message. A value of 1 for the Position parameter specifies that the attachment should be positioned at the beginning of the message body. A value 'n' greater than the number of characters in the body of the e-mail item specifies that the attachment should be placed at the end. A value of 0 makes the attachment hidden.
String
This parameter applies only if the mail item is in Rich Text format and Type is set to olByValue: the name is displayed in an Inspector object for the attachment or when viewing the properties of the attachment. If the mail item is in Plain Text or HTML format, then the attachment is displayed using the file name in the Source parameter.
Return Value
An Attachment object that represents the new attachment.
Our computers were upgraded to Office 2007. The following script fails to work on 2007, but works in 2003.
Look for the comment FAILS HERE
CreateObject("Outlook.Application") returns an error that the ActiveX object cannot be created:
Thanks for your help!!
Navy Firefighting Engineer
Ответы
Can you run this script on one of the systems with Outlook 2007 installed and post the exact message it prompts you with.
Knowing the error codes will help to determine the problem and resolution.
Is this still an open issue? Please advise. If there is no response within a week we will assume it is resolved and will close this post. Thanks
Все ответы
Can you run this script on one of the systems with Outlook 2007 installed and post the exact message it prompts you with.
Knowing the error codes will help to determine the problem and resolution.
Dim NS ' As NameSpace
Dim objOutlook ' As Application
' Dim objInbox As Outlook.MAPIFolder
Dim objFolder ' As Outlook.MAPIFolder
Dim Item ' As Object
Dim objItems ' As Object, MailItem but could be something else
Dim Icount ' Folder loop counter
Set NS = Nothing
set objOutlook = Nothing
strFolderName = "Public Folders/All Public Folders/USN/NAVAIR/ORLO/Functional Mailboxes/ORLO_498 MUSTER"
Const olFolderInbox = 6
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery _
("Select * From Win32_Process Where Name = 'outlook.exe'")
If colItems.Count > 0 Then wscript.echo "Outlook is running", 1
Set objOutlook = CreateObject("Outlook.Application")
Set objNamespace = objOutlook.GetNamespace("MAPI")
objNamespace.Logon "Default Outlook Profile",, False, True
Set objFolder = GetFolder(strFolderName)
wscript.echo "Using Mailbox: " & strFolderName
On Error Resume Next
wscript.echo ("LoadMailBox Messagecount=" & MessageCount), 1
wscript.echo "Loading Muster Mailbox content"
Set Item = objFolder.Items
'Set Item = objFolder.MailItems 'Outlook2007 seems to use MailItems instead of Items
On Error resume next
For Icount = 1 To MessageCount
' MessageCount comes from the count property of the folder in Outlook
wscript.echo "LoadMailBox, Icount = " & Icount & " MessageCount=" & MessageCount
wscript.echo "SentOn = " & Item(Icount).SentOn
'Outlook 2007 is having trouble with the item properties below
'Is it perhaps because the Outlook ObjectModell has changed?
wscript.echo "SenderName = " & Item(Icount).SenderName
if err.number <> 0 then
wscript.echo "Sender Name has a problem, Error Number " & err.number & " " & err.Description
wscript.echo "Subject = " & Item(Icount).Subject
wscript.echo "Body = " & Item(Icount).Body
' ******************* LOADING OF MESSAGES INTO MEMORY IS COMPLETE *****************
' This means all the messages, regardless of date
wscript.echo MessageCount & " Muster Messages found in LoadMailBox, Reading Inbox complete."
Public Function GetFolder(strFolderPath)
' folder path needs to be something like:
' "Public Folders\All Public Folders\Company\Sales"
Dim objApp ' As Outlook.Application
Dim objNS ' As Outlook.NameSpace
Dim colFolders ' As Outlook.Folders
Dim objFolder ' As Outlook.MAPIFolder
Dim arrFolders ' As String array
On Error Goto 0
'On Error Resume Next
if dbg then wscript.echo "GetFolder path = " & strFolderPath, 1
if dbg then wscript.echo "Adjusted folder path = " & strFolderPath
Set objApp = CreateObject("Outlook.Application")
' If Outlook is not installed, the folder will be nothing
If Err.number <> 0 Then
wscript.echo "Function GetFolder, CreateObject Outlook.Application"
On Error Goto 0
Set objNS = objApp.GetNamespace("MAPI")
Set objFolder = objNS.Folders.Item(arrFolders(0))
On Error Resume Next
If Not objFolder Is Nothing Then
For I = 1 To UBound(arrFolders)
Set colFolders = objFolder.Folders
Set objFolder = Nothing
Set objFolder = colFolders.Item(arrFolders(I))
If Err.Number <> 0 then
Msgbox "It appears that you do not have access permissions to the Muster Mailbox, call the Mailbox Owner"
if dbg then wscript.echo "Folder = " &objFolder, 1
If objFolder Is Nothing Then
Set GetFolder = objFolder
'If Dbg Then MsgBox("Getfolder is returning " & GetFolder)
On Error Resume Next
Set colFolders = Nothing
Set objNS = Nothing
Set objApp = Nothing
On Error Goto 0
Outlook is running
Using Mailbox: Public Folders\All Public Folders\USN\NAVAIR\ORLO\Functional Mail
Читайте также: