使用MS中的这段VBA代码,如果它执行得太频繁,我将得到一个错误。我发现清除它的唯一方法是重新启动我的电脑。知道为什么我能做些什么吗?
Public Function HasOutlookAcct(strEmail As String) As Boolean
Dim OutMail As Object
Dim OutApp As OutLook.Application
Dim objNs As OutLook.NameSpace
Dim objAcc As Object
'https://stackoverflow.com/questions/67284852/outlook-vba-select-sender-account-when-new-email-is-created
Set OutApp = CreateObject("Outlook.Application")
Set objNs = OutApp.GetNamespace("MAPI")
For Each objAcc In objNs.Accounts
If objAcc.SmtpAddress = strEmail Then
HasOutlookAcct = True
Exit For
End If
Next
OutApp.Quit
Set objAcc = Nothing
Set objNs = Nothing
End Function
发布于 2022-11-01 22:02:51
密码看上去不错。NameSpace.Accounts属性返回一个Accounts
集合对象,该对象表示当前配置文件中的所有Account
对象。我不认为Outlook对象模型有任何广泛或大量的使用,但在检查某个特定帐户是否在Outlook中配置的方法中创建一个新的Outlook应用程序实例并不是使用Outlook的最佳方法。相反,我建议在某个时候运行Outlook,并获取所有配置好的电子邮件,以便在必要时保存以供将来使用。
同时,禁用所有的COM外接程序也是有意义的,看看它是否有帮助。此问题可能与任何特定的COM外接程序有关。
发布于 2022-11-02 14:08:42
似乎错误是通过考虑用户来解决的。
根据我的结果,假设当用户的实例使用outApp.Quit
关闭时,Outlook没有被完全清除。
当Outlook打开时,将不会应用outApp.Quit
,并且Outlook在结束时仍然处于打开状态。
当Outlook未打开时,将在后台打开它,然后用outApp.Quit
关闭它。
在任何时候,Outlook都有零个或一个实例。
Option Explicit
Public Function HasOutlookAcct(strEmail As String) As Boolean
'Reference Outlook nn.n Object Library
' Consistent early binding
Dim outApp As Outlook.Application
Dim objNs As Outlook.Namespace
Dim objAcc As Outlook.Account
Dim bCreated As Boolean
On Error Resume Next
Set outApp = GetObject(, "Outlook.Application")
On Error GoTo 0
If outApp Is Nothing Then
bCreated = True
Set outApp = CreateObject("Outlook.Application")
End If
Set objNs = outApp.GetNamespace("MAPI")
For Each objAcc In objNs.Accounts
'Debug.Print objAcc.SmtpAddress
If objAcc.SmtpAddress = strEmail Then
HasOutlookAcct = True
Exit For
End If
'Set objAcc = Nothing ' Additional cleanup if needed
Next
If bCreated = True Then ' Outlook object had to be created
outApp.Quit
End If
'Set outApp = Nothing ' Additional cleanup if needed
Set objNs = Nothing
End Function
Private Sub HasOutlookAcct_Test()
Dim x As Boolean
Dim sEmail As String
sEmail = "someone@somewhere.com"
Dim i As Long
For i = 1 To 50
Debug.Print i & ": " & sEmail
x = HasOutlookAcct(sEmail)
Debug.Print " HasOutlookAcct: " & x
DoEvents
Next
Debug.Print "done"
End Sub
https://stackoverflow.com/questions/74269722
复制相似问题