This is a followup to a previous question I had asked. Thank you to the community for your help with that.
I'm trying to create WithEvents code for the first time to check a folder for new items. Eventual plan is to use the ItemsAdd event to trigger a bunch of other processing, but for now, just trying to save it to a folder and not getting that far.
When I run the Application_Startup code below, the immediate window shows that I've found the right clntFldrItms. Problem is, if I then drag an item into the folder in question, the ItemAdd macro doesn't fire. When I try to add a watch for clntFldrItms, the variable isn't set to anything. It looks like as soon as the Application_Startup sub finishes, the assignment stops.
All code is in the ThisOutlookSession object.
Could this be because I'm working with an SMTP email address (rather than Exchange, for example)?
Thanks again for your help.
EDIT Adding my response to Eugene's comment. I noticed that when I open the editor and step into the Application_Startup sub, clntFldrItms is properly assigned, even before I get to the Set clntFldrItms = clntFldr.Items line. As soon as I finish stepping through, it's gone again. I can't step into the ItemAdd sub, but when I step into other code clntFldrItms is Nothing.
FINAL EDIT Sorry, I realize I forgot to close this off. I wasn't able to solve the problem per se, but I realized it was due to my SMTP account. When I tried it at work with Exchange, it worked. It seems that the event doesn't fire unless I'm working in Exchange.
Option Explicit
Public WithEvents clntFldrItms As Outlook.Items
Private Sub Application_Startup()
Dim clntFldr As MAPIFolder
Set clntFldr = Application.Session.GetDefaultFolder(olFolderSentMail).Folders("Client Emails")
Set clntFldrItms = clntFldr.Items
Set clntFldr = Nothing
Debug.Print clntFldrItms.item(1).Subject
End Sub
Private Sub clntFldrItms_ItemAdd(ByVal item As Object)
Dim bChar As String
bChar = "\/:*?™""® <>|.&@#_+`©~;-+=^$!,'" & Chr(34)
Dim saveName As String
If item.Class = olMail Then
saveName = item.Subject
For x = 1 To Len(bChar)
saveName = Replace(saveName, Mid(bChar, x, 1), "-")
Next x
item.SaveAs "C:\Users\User\Google Drive\8 - VBA work\Preparation for Assisted Responder\Sent Messages Folder\" & _
saveName & ".msg", olMSG
End If
End Sub