Outlook 2013 VBA: store user defined settings - vba

Currently at the office we have Outlook 2003. We will be migrating to Outlook 2013.
In Outlook 2003 we have a commandbar that as example saves a mail item to a user specified folder or moves the item to the desired team.
In a userform the end-user can set his settings to his desired folder or select the team he is currently on. In this settings form there are multiple input field the user can fillout.
Whenever he clicks a button on the commandbar, outlook checks his settings to see on what team he is on, his desired save folder is, etc.
This userdefined settings are stored and called on by it's tags
(Application.ActiveExplorer.CommandBars("Toolbar").Controls.Item(1).tag)
As far i found on the internet Outlook 2013 does not support commandbars. I can instal the commandBar, but as soon as you restart outlook the bar is gone and the settings are gone.
Is there a way to save/store the settings made by the end-user in a userform so the scripts saves the mail item based on his settings to the correct folder or team?
I've tried to find a solution but haven't found it yet, or do not know where to look.
Hope you can guide me into the right direction to look for a solution.
(note: I know a little bit of VBA, can read and write it, but found it hard to explain how it works. If i left out some critical information in the question please let me know.)

Outlook doesn't allow to customize the Ribbon UI using VBA. The only thing you can do is to assign a macro to QAT button (or add controls manually in Outlook).
You need to develop an add-in to be able to customize the Ribbon UI (aka Fluent UI). See Walkthrough: Creating a Custom Tab by Using the Ribbon Designer for more information.
Read more about the Fluent UI in the following series of articles in MSDN:
Customizing the 2007 Office Fluent Ribbon for Developers (Part 1 of 3)
Customizing the 2007 Office Fluent Ribbon for Developers (Part 2 of 3)
Customizing the 2007 Office Fluent Ribbon for Developers (Part 3 of 3)
Is there a way to save/store the settings made by the end-user in a userform so the scripts saves the mail item based on his settings to the correct folder or team?
Using the Tag property is not the best way to store the user settings. Of course, you can standard ways for storing settings on the PC - files (XML, text or your own binary format), windows registry and etc.
But the Outlook object model provides hidden items for that. The GetStorage method of the Folder class returns a StorageItem object on the parent Folder to store data for an Outlook solution. See Storing Data for Solutions for more information.

As promised a few code samples wich i used to store and get the settings.
Maybe not the best way to do it, but it solved my problem to store the settings and maybe it could help someone else.
First of all I made a little check to see if the settings are already there.
Function Hidden_Settings_Aanwezig() As Boolean
Dim oNs As Outlook.Namespace
Dim oFL As Outlook.folder
Dim oItem As Outlook.StorageItem
On Error GoTo OL_Error
Set oNs = Application.GetNamespace("MAPI")
Set oFld = oNs.GetDefaultFolder(olFolderInbox)
Set oItem = oFld.GetStorage("Hidden Settings", olIdentifyBySubject)
If oItem.Size <> 0 Then
Hidden_Settings_Aanwezig = True
Else
Hidden_Settings_Aanwezig = False
End If
Exit Function
OL_Error:
MsgBox (Err.Description)
Err.Clear
End Function
If not, the following code creates the settings based on tekstboxes and checkboxes on a userform with the following code
Function Maak_Settings_Hidden()
Dim oNs As Outlook.Namespace
Dim oFld As Outlook.folder
Dim oSItem As Outlook.StorageItem
On Error GoTo OL_Error
Set oFld = Application.Session.GetDefaultFolder(olFolderInbox)
Set oSItem = oFld.GetStorage("Hidden Settings", olIdentifyBySubject)
'repeat the next to lines for every setting you want to store
oSItem.UserProperties.Add "Export Folder", olText
oSItem.UserProperties("Export Folder").Value = TextBox1.Text
oSItem.Save
Exit Function
OL_Error:
MsgBox (Err.Description)
Err.Clear
End Function
The functions above are called on with the following code:
If Hidden_Settings_Aanwezig = True Then
Call Get_Hidden_Settings_Startup
Else
Maak_Settings_Hidden
End If
To use one of the settings i use the following code.
In the main sub I use the following line:
DestFolder = Get_Hidden_Settings("Export Folder")
To call on this function:
Function Get_Hidden_Settings(Setting) As String
Dim oNs As Outlook.Namespace
Dim oFL As Outlook.folder
Dim oItem As Outlook.StorageItem
On Error GoTo OL_Error
Set oNs = Application.GetNamespace("MAPI")
Set oFld = oNs.GetDefaultFolder(olFolderInbox)
Set oItem = oFld.GetStorage("Hidden Settings", olIdentifyBySubject)
If oItem.Size <> 0 Then
Get_Hidden_Settings = oItem.UserProperties(Setting)
End If
Exit Function
OL_Error:
MsgBox (Err.Description)
Err.Clear
End Function

If I understand your problem correctly, what I would do is the following:
1) Export your VBA stuff into a *.bas files (for modules) and *.frx (for user forms) This is done in the VBA editor, File --> Export. You do this for each item (module and user form). Save these files e.g. on a memory stick, or whereever it suits you.
2) Import these files in Outlook 2013 into the VBA editor (same way, but --> File --> Import of course) e.g. by loading them from your memory stick.
This should make your VBA code available in your new Outlook 2013 environment.
3) Your command bars will not be available. But you can easily create something else: In the Office 2013 (etc.) products, you can add stuff to the "Ribbon". E.g. you can create a new tab called "My self-made tools", and you can place buttons there that call your VBA procedures. There you will find buttons for "Create new..."
To do so: --> File --> Optiobs --> Customize Ribbon --> Macros
Note: In a standard installation of Office 2013 (etc.) you will not have access to the VBA editor. To make the editor available, go through --> File --> Options --> Customize Ribbon and set a tick mark in the field for "Develooper tools". This will make a tab of that name appear in the "Ribbon".

Related

How to bypass MSAccss AutoExec macro and bypass Startup form

How do I bypass the MSAccess autoexec macro and startup form for a deep-legacy code upgrade of a large MS Access 2003 application with hundreds of forms and reports?
It is an upgrade from Access 2003 to Access 2016, 2019 or 365.
This is a mission critical system kept alive and on crutches for 15 years without any VBA code updates.
Files in the application
Multiple MSAccess files in MDB and ACCDB format
No MSAccess files in MDE or ACCDE formats with compiled VBA code
No MSAccess other files wuch as mdw security files
I run a dos command for the database - PATH_TO_MSACCESS.exe DB_NAME.mdb
I'm using MSAccess.exe 32 bit from Office 365.
Note that there are compatibility and VBA compiler errors if you run on a 64 bit MSAccess.exe if the VBA calls Windows operating system Win32 API methods. This app calls a few (5) Win32 API calls. Technical, MS Access 64 bit will treat some 32 bit data sent in/returned from the Win32 API as 64 bit causing errors.
The most difficult part is that many of the web pages and nearly all Microsoft pages related to this have been deleted from the web.
Tried but did not work
Holding down shift key when you open the MSAccess database
Hitting F11 to open the Navigation Pane in Access (does not open). If Navigation Pane opens I could edit the AutoExec macro or the startup form's Form_Open code
Tried, not perfect, and works
Run a macro which does not exist on MSAccess.exe command line, hit escape multiple times on the error messages, the click on the MSAccess ribbon to get to the VBA code. Messy, but it gets me into the VBA code.
Added a "Stop" as the first line of the macro named "autoexec" and also as the first line of the startup form's "Form_Open()" method. I had to add an empty "Form_Open()" event handler for the form
Current status:
The application runs OK on a machine with MS Access version before 2016
It fails multiple ways when only 32 bit MS Access 365/2019 is installed on the machine.
I have been finding and fixing things like bad configuration file entries, incorrect installation path, etc. but need to debug the VBA startup code and initial form load in the VBA debugger.
I cannot directly get into the VBA debugger on the first line of the AutoExec macro or start up form's Form_Open function. MSAccess always runs the autoexec macro and shows the startup form.
I can get into the VBA by running MSaccess.exe command line and specifying that it runs a macro which does not exist.
Here are possible solutions based on Google searching broken out by Access version since the code/database settings in question could be specific to any Access version from 95 to 2010.
Access 2007: Opening an MS-Access database from the command line without running any of the startup vba code?
Hold down shift key when opening MDB database
Access XP
Open access database without executing scripts or forms
Hold down shift key when opening the Access database
Remove AutoExec macro
Remove the startup form setting from the database
Access 2007:
Emulating a SHIFT key press when using VBA to open an ms-access database secured by an mdw file?
Slightly different case where the Access database is secured by a MDW security file
Same answers
Access XP/2003/2007?
How to skip Autoexec macro when opening MSAccess from MSAccess?
Method One:
Original URL is dead, Internet Archive Wayback machine has an archived copy: https://web.archive.org/web/20101204113950/http://www.mvps.org/access/api/api0068.htm
Send Shift key to Access via code to bypass startup macro if the [AllowbypassKey] is not set
Method Two:
Extract the Autoexec macro from the database, replace it with a blank AutoExec macro
Uses DoCmd.DatabaseTransfer acImport and DoCmd.DatabaseTransfer acExport
Method Three:
Rename the AutoExec macro using VBA code
OpenCurrentDatabase ("Your database")
DoCmd.Rename "Autoexec", acMacro, "tmp_Autoexec"
CloseCurrentDatabase
MS Access keyboard short cuts for getting at the VBA code or objects in an Access database. From https://support.microsoft.com/en-us/office/keyboard-shortcuts-for-access-70a673e4-4f7b-4300-b8e5-3320fa6606e2
I haven't tried the MSAccess keyboard short cuts to see if they let me open and view the Access VBA code, toolbars, table/form dedign viewer, or switch to code editing mode. I've included them here for completeness.
F2 - Switch between Edit mode (with insertion point displayed) and Navigation mode in the Datasheet or Design view
F4 - Open properties pane for an object
F5 - Switch to Form view from the form Design view
F6 - Switch between panes in the MS Access interface
F10 (?) unhide the ribbon
F11 - Show or hide the Navigation Pane
Alt-X, Alt-X,1 - Open the External Data tab in the ribbon
Alt-Y - Open the Database Tools tab in the ribbon
Alt-J,T - Open the Table tab in the ribbon
Alt-X,2 - Open the Add-ins tab in the ribbon
Control-F1 - Expand/collapse the ribbon
Alt-F11 - Switch to/from the VBA editor
Show or hide the MSAccess ribbon toolbar in VBA code. Included here for completeness. This application hides the ribbon bar on application startup.
MSAccess - Minimize the Toolbar Ribbon OnLoad()?
MSAccess 2010 onwards. The acToolbarNo is in the VBA code for this application
DoCmd.ShowToolbar "Ribbon", acToolbarNo 'Hides the full toolbar
DoCmd.ShowToolbar "Ribbon", acToolbarYes 'Show
MSACcess 2010, 2013
CommandBars.ExecuteMso "MinimizeRibbon"
Before MSAccess 2010
SendKeys "^{F1}", False
Special case: You may get an error on the Access startup form if it has a record source which has an error. this is not the case for my application but included here completeness
difficulty tracing microsoft access VBA code
Special case: You get an infinite loop of dialog prompts or errors from the startup form. Hold down the "Control-Break" key while clicking on OK for the error message to break out of the loop of errors. https://bettersolutions.com/vba/debugging/index.htm
It may be possible to break out of the main startup form to the MS Access object explorer by right clicking on the startup form's title bar or right click on the startup form's body.
Right clicking on the startup form's title bar has these menu commands
Save
Close and Close All
Form View
Layout View
Design View
Right clicking on the startup form's body has these menu commands
Form View
Layout View
Design View
Cut, Copy, Past (disabled)
Form Properties (disabled)
Properties (disabled)
Close
the other thing to check? Are you using a shortcut? if it has the /runtime swtich in it, then the shift key will be ignored NO MATTER what you do, and even if no shfit key by-pass code (to disable) shift key means the shift key will STILL be ignored. So, you want to ensure that you not launching/using a shortcut.
you also want to check/ensure/find out/be aware if the application has workgroup security. Again, in 99 out of 100 cases, the shortcut will show this.
next up:
is this a mdb, or mde file? The mde file is a compiled version. No source code exists, and you can't modify the mde. So, again, ensure that you have a mdb file for the front end, not a mde. If you don't have that mdb, then you are in big trouble - you don't have the source code.
You have all this info in your post, but you leave out the most important issues.
So, is this a mde, or mdb? You need to know this.
Is there a worgroup security file (mdw) specifed in the link that is typical used to launch the application. If workgroup secuirty is involed, then the logon id you use might get you past shift key, but then that user might not have been given design rights, so at that point, shify key by-pass will be of zero use to get into the code.
I mean, launch your copy of access 2016 or whatever. Then try to import the objects from that database. This way you don't have to use or ever worry about shfit key, but are doing a simple import of the forms, reports and code into a brand new fresh database.
So, another question:
Don't bother launching the application - create a blank new database, and then import from the existing - can you do this? (doing this does NOT copy the shift key setting of the original database).
MSAccess command line lets you tell it what macro to execute on startup.
I ran the following cmd.exe command line which generates multiple errors and allows you to get into the Access database with the navigator and get into the VBA code. Not the best solution but one possibility.
MSAccess.exe DB /X ADEEERETDEREAR
DB is the full path to the Access database
ADEERETDEREAR is a macro which does not exist
Access 2007?
How to disable Macro and Start-Up values while opening the MS Access DB
Access 2003?
Bypasss shift key. These link to Zip files projects available for download
https://web.archive.org/web/20071214172548/http://www.members.shaw.ca/AlbertKallal/msaccess/msaccess.html
https://web.archive.org/web/20071214172548/http://www.members.shaw.ca/AlbertKallal/msaccess/shiftkey.zip
https://web.archive.org/web/20071214172548/http://www.members.shaw.ca/AlbertKallal/msaccess/shiftkey2000.zip
Access 2007:
remove autoexec macro from MS Access 2007
Create new macro and then rename it in the Access UI to autoexec, say yes to the prompt to overwrite the existing AutoExec macro
Access 2010?
Opening an MS-Access database from the command line without running any of the startup vba code?
Access ?
Disable F11 Key in MS Access to prevent opening the Navigation Pane
Open the Access database, let the main form be shown
Hit F11 to show the navigation pane
A guess that one could modify the autoexec macro and/or the startup form from the navigation pane
Access ?
https://bytes.com/topic/access/answers/211664-programatically-set-startup-form
A guess that you could use VBA in one Access database to open the target database
Get the name of the startup form
Change the startup form's name or maybe blank out the startup form's name
VBA code similar to CurrentDB.Properties("StartupForm") = "MyForm"
Another guess would be to blank out the startup form's name in the database properties
Same may work for the autoexec macro
Access 2010?
Reset startup form to nothing in VBA code
Code from 2012 is here: https://www.tek-tips.com/viewthread.cfm?qid=1673392
First way
Dim strOriginalForm as String
Dim db as Database
Sub RemoveStartup()
Set db = OpenDatabase(yourdatabase)
strOriginalForm = db.Properties("StartUpForm")
db.Properties("StartUpForm") = "(none)"
db.Close
set db = Nothing
End Sub
Sub ResetStartup()
Set db = OpenDatabase(yourdatabase)
db.Properties("StartUpForm") = strOriginalForm
db.Close
Set db = Nothing
End Sub
Second way
Set prp = db.CreateProperty("AllowByPassKey", dbBoolean, True)
db.Properties.Append prp
Third way
Delete the property using - database.properties.delete propertyname
A more complete example from the same page exists.
I have not tried to import the Access objects into a new database. (Thanks Albert Kallal for the information)
This would allow me to look at the VBA code. It may not work as a replacement for the original database with all of the settings internal to the database.
How to import the Access objects from another Access database:
https://support.microsoft.com/en-us/office/import-database-objects-into-the-current-access-database-23aea08b-7487-499d-bdce-0c76bedacfdd
Access 365 steps (likely works for Access 2016)
External Data tab in ribbon
Click New Data Source -> From Database -> Access in the Import & Link ribbon group
Get External Data - Access Database window is shown
Browse for the MSAccess database MDB or ACCDB file in the File Name Field
The Import Objects window is shown
Select the tables, queries, forms, reports macros, modules to import
In the Options button dialog, you can select menus, toolbars, etc. to import
Click on OK
For Names duplicated, Access will append a 1,2,3 to the end of an imported object's name
Access 2010?
Reset startup form to nothing in VBA code
Code from 2012 is here: https://www.tek-tips.com/viewthread.cfm?qid=1673392
Fourth way as mentioned above
A more complete example from the same page.
Code from 2012 is here: https://www.tek-tips.com/viewthread.cfm?qid=1673392
Public Sub GetCBs()
Dim db As DAO.Database
Dim strPath As String
Dim startUpform As String
Dim app As Access.Application
Dim custBars As Collection
Dim custShortCutBars As Collection
Dim custNonShortCutBars As Collection
Dim i As Integer
Dim blnAutoexec As Boolean
strPath = GetOpenFile()
'Get the db without opening in application
Set db = getDb(strPath)
'Get startupform
startUpform = getStartUp(db)
'Turn off the start up form
TurnOffStartUp db
'Check for and auto exec. If exists import and replace
If hasAutoexec(db) Then
blnAutoexec = True
ImportAutoExec (strPath)
End If
Set app = New Access.Application
'Open safely
app.OpenCurrentDatabase (strPath)
'Read command bars
Set custBars = getCustBars(app)
Set custShortCutBars = getCustShortCutBars(app)
Set custNonShortCutBars = getCustNonShortCutBars(app)
app.CloseCurrentDatabase
Set db = app.CurrentDb
Set db = getDb(strPath)
'Return start up form
TurnOnStartUp db, startUpform
db.Close
'Return auto exec
If blnAutoexec Then
ReturnAutoExec (strPath)
End If
Debug.Print "all custom bars:"
'All bars
For i = 1 To custBars.Count
Debug.Print custBars(i)
Next i
'Do something with the command bars
Debug.Print "all shortcut bars:"
'Short cut only
For i = 1 To custShortCutBars.Count
Debug.Print custShortCutBars(i)
Next i
'Not short cut
Debug.Print "Non shortCut"
For i = 1 To custNonShortCutBars.Count
Debug.Print custNonShortCutBars(i)
Next i
End Sub
Public Function getDb(strPath As String) As DAO.Database
Set getDb = DBEngine(0).OpenDatabase(strPath)
End Function
Public Function getCustBars(app As Access.Application) As Collection
' all bars
Dim col As New Collection
Dim cb As Object
For Each cb In app.CommandBars
If cb.BuiltIn = False Then
col.Add (cb.Name)
End If
Next cb
Set getCustBars = col
End Function
Public Function getCustShortCutBars(app As Access.Application) As Collection
' only short cut bars
Dim col As New Collection
Dim cb As commandbar
For Each cb In app.CommandBars
If cb.BuiltIn = False Then
If cb.Type = msoBarTypePopup Then
col.Add (cb.Name)
End If
End If
Next cb
Set getCustShortCutBars = col
End Function
Public Function getCustNonShortCutBars(app As Access.Application) As Collection
' Menu bars that are not shortcut bars
Dim col As New Collection
Dim cb As commandbar
For Each cb In app.CommandBars
If cb.BuiltIn = False Then
If cb.Type <> msoBarTypePopup Then
col.Add (cb.Name)
End If
End If
Next cb
Set getCustNonShortCutBars = col
End Function
Public Function getStartUp(db As DAO.Database) As String
Dim prp As DAO.Property
For Each prp In db.Properties
If prp.Name = "startupform" Then
getStartUp = prp.Value
Exit For
End If
Next
End Function
Public Sub TurnOffStartUp(db As DAO.Database)
Dim prp As DAO.Property
For Each prp In db.Properties
If prp.Name = "startupform" Then
prp.Value = "(None)"
Exit For
End If
Next
End Sub
Public Sub TurnOnStartUp(db As DAO.Database, strFrm As String)
Dim prp As DAO.Property
For Each prp In db.Properties
If prp.Name = "startupform" Then
prp.Value = strFrm
Exit For
End If
Next
End Sub
Public Sub ImportAutoExec(strPath As String)
On Error GoTo errLbl
DoCmd.TransferDatabase acImport, "Microsoft Access", strPath, acMacro, "AutoExec", "AutoExecBackup"
DoCmd.TransferDatabase acExport, "Microsoft Access", strPath, acMacro, "TempAutoExec", "AutoExec"
Exit Sub
errLbl:
If Err.Number = 7874 Then
Debug.Print "Auto Exec macro does not exist"
Else
MsgBox Err.Number & " " & Err.Description
End If
End Sub
Public Sub ReturnAutoExec(strPath As String)
On Error GoTo errLbl
DoCmd.TransferDatabase acExport, "Microsoft Access", strPath, acMacro, "AutoExecBackup", "AutoExec"
DoCmd.DeleteObject acMacro, "AutoExecBackup"
Exit Sub
errLbl:
If Err.Number = 7874 Then
Debug.Print "Auto Exec macro does not exist"
Else
MsgBox Err.Number & " " & Err.Description
End If
End Sub
Public Function hasAutoexec(db As DAO.Database) As Boolean
Dim rs As DAO.Recordset
Dim strSql As String
strSql = "SELECT MSysObjects.Name FROM MSysObjects WHERE MSysObjects.Name = 'AutoExec' AND MSysObjects.Type = -32766"
Set rs = db.OpenRecordset(strSql)
If Not (rs.EOF And rs.BOF) Then
hasAutoexec = True
End If
End Function

How do I set the default save format in PowerPoint?

Microsoft, in their infinite wisdom, decided that the default file format for Office 2010 applications should be the format that was 13 years old (Office 97-2002) at the time of release.
The newer formats (2007 and newer) save the data in compressed XML files which are much smaller, and also allow for many additional features. Our corporate IT department hasn't or can't set a group policy to force users to default to saving in the new format, so I'm writing a macro to adjust the settings for everyone in our department.
I can do this in Excel and Word very simply by executing the following VBA code (I'm running it from an Excel workbook):
Public Sub SetExcelSave()
Dim myExcel As Excel.Application
Set myExcel = New Excel.Application
Excel.DefaultSaveFormat = xlOpenXMLWorkbook
Excel.Quit
Set Excel = Nothing
End Sub
Public Sub SetWordSave()
Dim myWord As Word.Application
Set myWord = New Word.Application
Word.DefaultSaveFormat = wdFormatDocumentDefault
Word.Quit
Set Word = Nothing
End Sub
However, I haven't been able to find the appropriate setting to adjust in PowerPoint. Does anyone know where that property is or what it's called?
This code will not compile cleanly, giving an error on the PPT.DefaultSaveFormat line:
Public Sub SetPowerPointSave()
Dim PPT As PowerPoint.Application
Set PPT = New PowerPoint.Application
PPT.DefaultSaveFormat = ppSaveAsOpenXMLPresentation
PPT.Quit
Set PPT = Nothing
End Sub
I've rummaged around in the Office Application Object documentation for PowerPoint, but I'm just not finding what I'm after. It's highly likely that I just don't know what I'm looking for and have simply overlooked it.
Does anyone know what property I'm supposed to set to be able to programmatically change this?
The default save format for PPT 2007 and later is the new XML format (PPTX rather than PPT and so on). If the user (or IT staff via policies) have overridden this in the File | Save | Save files in this format: then the default becomes whatever they've selected, for whatever reason.
App-wide defaults like this typically aren't exposed via the object model; they're stored in the registry. In this case, in
HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\PowerPoint\Options
DefaultFormat DWORD=27 for PPTX
Substitute the correct version for 14.0 above; 12.0 for PPT 2007, 14.0 for 2010, and so on (no 13.0).
If you can write the value you want to the registry when PPT isn't running, you can reset the defaults. If you write to the reg while PPT's running, it won't affect the current instance of PPT, and your changes will be overwritten when PPT quits.

Outlook VBA stops functioning the next day

I have VBA code in Outlook I use to send specific emails (with three asterics in the subject line) to the deleted folder after sent in 'This Outlook Session'.
It works correctly when Outlook is first opened, and all day long, however, the next day I find at some point overnight the VBA code has failed to function and only functions properly again if I close \ re-open Outlook??
This only started to occur when the company moved to the 2007 & 2010 versions.
I need it to run constantly on sent mail as I have early am batch processes that send out a lot of emails that I want to have removed from sent folder and placed in the deleted folder after eachis sent as this code does.
Here is the code. Since it worked well before, I can only assume the newer Outlook versions need some additional trigger to keep 'This Outlook Session' open or something of that nature.
Any thoughts would be appreciated.
Option Explicit
Private WithEvents olSentItems As Items
Private Sub Application_Startup()
Dim objNS As NameSpace
Set objNS = Application.GetNamespace("MAPI")
Set olSentItems = objNS.GetDefaultFolder(olFolderSentMail).Items
End Sub
Private Sub olSentItems_ItemAdd(ByVal Item As Object)
If Item.Class = olMail And InStr(1, Trim(Item.Subject), " * * * ", vbTextCompare) > 0 _
Then
Item.Delete
End If
End Sub
I suggest that you have a look at the Trust Center Settings >> Macros. Office 2003 has it in a different way and it is all new after Office 2003.
Try different settings and see which one fits your need. They are totally four setting levels.
Also it is good idea to use only one version of Outlook. Don't interchange between 2007 and 2010 if you have both of them. Outlook versions cannot co exist with creation of bugs.
This page should be able to give me more details.
Click Here

How do I make Outlook purge a folder automatically when anything arrives in it?

I hope it's okay to ask this kind of question. Attempting to write the code myself is completely beyond me at the moment.
I need a macro for Outlook 2007 that will permanently delete all content of the Sent Items folder whenever anything arrives in it. Is it possible? How do I set everything up so that the user doesn't ever have to click anything to run it?
I know I'm asking for a fish, and I'm embarrassed, but I really need the thing...
edit:
I've pasted this into the VBA editor, into a new module:
Public Sub EmptySentEmailFolder()
Dim outApp As Outlook.Application
Dim sentFolder As Outlook.MAPIFolder
Dim item As Object
Dim entryID As String
Set outApp = CreateObject("outlook.application")
Set sentFolder = outApp.GetNamespace("MAPI").GetDefaultFolder(olFolderSentMail)
For i = sentFolder.Items.Count To 1 Step -1
sentFolder.Items(i).Delete '' Delete from mail folder
Next
Set item = Nothing
Set sentFolder = Nothing
Set outApp = Nothing
End Sub
It's just a slightly modified version of a piece of code I found somewhere on this site deleting Deleted Items. It does delete the Sent Items folder when I run it. Could you please help me modify it in such a way that it deletes Sent Items whenever anything appears in the folder, and in such a way that the user doesn't have to click anything to run it? I need it to be a completely automated process.
edit 2: Please if you think there's a better tool to achieve this than VBA, don't hesitate to edit the tags and comment.
edit 3: I did something that works sometimes, but sometimes it doesn't. And it's ridiculously complicated. I set a rule that ccs every sent email with an attachment to me. Another rule runs the following code, when an email from me arrives.
Sub Del(item As Outlook.MailItem)
Call EmptySentEmailFolder
End Sub
The thing has three behaviors, and I haven't been able to determine what triggers which behavior. Sometimes the thing does purge the Sent Items folder. Sometimes it does nothing. Sometimes the second rule gives the "operation failed" error message.
The idea of acting whenever something comes from my address is non-optimal for reasons that I'll omit for the sake of brevity. I tried to replace it with reports. I made a rule that sends a delivery report whenever I send an email. Then another rule runs the code upon receipt of the report. However, this has just one behavior: it never does anything.
Both ideas are so complicated that anything could go wrong really, and I'm having trouble debugging them. Both are non-optimal solutions too.
Would this be an acceptable solution? Sorry its late but my copy of Outlook was broken.
When you enter the Outlook VB Editor, the Project Explorer will be on the left. Click Ctrl+R if it isn't. It will look something like this:
+ Project1 (VbaProject.OTM)
or
- Project1 (VbaProject.OTM)
+ Microsoft Office Outlook Objects
+ Forms
+ Modules
"Forms" will be missing if you do not have any user forms. It is possible "Modules" is expanded. Click +s as necessary to get "Microsoft Office Outlook Objects" expanded:
- Project1 (VbaProject.OTM)
- Microsoft Office Outlook Objects
ThisOutlookSession
+ Forms
+ Modules
Click ThisOutlookSession. The module area will turn white unless you have already used this code area. This area is like a module but have additional privileges. Copy this code to that area:
Private Sub Application_MAPILogonComplete()
' This event routine is called automatically when a user has completed log in.
Dim sentFolder As Outlook.MAPIFolder
Dim entryID As String
Dim i As Long
Set sentFolder = CreateObject("Outlook.Application"). _
GetNamespace("MAPI").GetDefaultFolder(olFolderSentMail)
For i = sentFolder.Items.Count To 1 Step -1
sentFolder.Items(i).Delete ' Move to Deleted Items
Next
Set sentFolder = Nothing
End Sub
I have taken your code, tidied it up a little and placed it within an event routine. An event routine is automatically called when the appropriate event occurs. This routine is called when the user has completed their log in. This is not what you requested but it might be an acceptable compromise.
Suggestion 2
I have not tried an ItemAdd event routine on the Sent Items folder before although I have used it with the Inbox. According to my limited testing, deleting the sent item does not interfere with the sending.
This code belongs in "ThisOutlookSession".
Option Explicit
Public WithEvents MyNewItems As Outlook.Items
Private Sub Application_MAPILogonComplete()
Dim NS As NameSpace
Set NS = CreateObject("Outlook.Application").GetNamespace("MAPI")
With NS
Set MyNewItems = NS.GetDefaultFolder(olFolderSentMail).Items
End With
End Sub
Private Sub myNewItems_ItemAdd(ByVal Item As Object)
Debug.Print "--------------------"
Debug.Print "Item added to Sent folder"
Debug.Print "Subject: " & Item.Subject
Item.Delete ' Move to Deleted Items
Debug.Print "Moved to Deleted Items"
End Sub
The Debug.Print statements show you have limited access to the sent item. If you try to access more sensitive properties, you will trigger a warning to the user that a macro is assessing emails.

Adjusting a VB Script to Programmatically Create a Folder triggered by an E-mail

This is my first time asking a question to y'all. I'm a SQL Developer by trade, and am very green when it comes to VB.
I manage a on-line database for my department, Quickbase, and with this website we manage report requisitions. I create a ticket for each one, and that ticket creates an e-mail notifying the dev. responsible for that assignment. We have folders set up for each request that comes in, and it is very laborious and frustrating to manually create said folders.
So I asked and looked around, coming across a script that was able to do what I needed, or so I am told. However, I'm not sure how to customize it to my needs, nor implement it correctly. This is where I need your assistance, fair programming gods of SO, please help me slay this dragon, and all the riches of the realm will be yours*!
Outlook VBA
Sub MakeFile(MyMail As MailItem)
myMailEntryID = MyMail.EntryID
Set outlookNameSpace = Application.GetNamespace(“MAPI”)
Set outlookMail = outlookNameSpace.GetItemFromID(myMailEntryID)
MyArgument = OutlookMail.Subject
Dim sMyCommand = “c:\makefile.bet ” & MyArgument
Shell “cmd /c ” & sMyCommand, vbHide
End Sub
Makefile.bat
#echo off
cls
mkdir %1
The webtsite URL is: www.quickbase.com
The root folder path: h:///ntsp/data/reports - criteria/quickbase docs/[Folder to be created]
*Riches are not monetary, but the feeling of goodness, and completeness only gained by helping a fellow nerd out, oh and it makes the e-peen grow might and strong!
being a fellow nerd I am going to get you started in the right direction. I think we can achieve what you want with VBA alone and do not need to use shell.
First we need to hook an event of when this all should happen. I imagine that is when your inbox gets an email. If I am right here is the start of this.
Please understand 2 important things.
This only works on items coming into your inbox. Thus if you already have a rule moving items to another folder it will not work.
You need to "Test" the email coming in - my example shows a test of the subject. It will only call you special routine IF and ONLY IF the subject has in it "My Test"
To enter the code in the Visual Basic Editor:
On the Tools menu, point to Macro, and then click Visual Basic Editor.
In the Project pane, click to expand the folders, and then double-click the ThisOutlookSession icon.
Type or paste the following code into the Code window.
Dim WithEvents objInboxItems As Outlook.Items
' Run this code to start your rule.
Sub StartRule()
Dim objNameSpace As Outlook.NameSpace
Dim objInboxFolder As Outlook.MAPIFolder
Set objNameSpace = Application.Session
Set objInboxFolder = objNameSpace.GetDefaultFolder(olFolderInbox)
Set objInboxItems = objInboxFolder.Items
End Sub
' Run this code to stop your rule.
Sub StopRule()
Set objInboxItems = Nothing
End Sub
' This code is the actual rule.
Private Sub objInboxItems_ItemAdd(ByVal Item As Object)
If Item.Subject = "My Test" Then
Call checkForFolder
End If
End Sub
Private Sub checkForFolder()
End Sub
On the File menu, click Save VbaProject.OTM.
You can now run the StartRule and StopRule macros to turn the rule on and off.
Quit the Visual Basic Editor.
(You might need to start and stop Outlook to get the variables to "Hook".
Once you get this working and understood, then you can remove the on off switches.
Then you have to decide your test for making a new folder so that we can then test the email and compare it to existing folders and then make a new one etc.