I want to use built-in Open File dialog from my VSTO add-in. I have to set InitialFileName when showing the dialog. Unfortunately, this property does not exist in the Dialog class:
var Dlg = Word.Dialogs.Item(WdWordDialog.wdDialogFileOpen);
Dlg.InitialFileName = SomePath; //COMPILE ERROR: no such property
Try to cast it to FileDialog also doesn't work:
var Dlg = Word.Dialogs.Item(WdWordDialog.wdDialogFileOpen) as FileDialog;
Dlg.InitialFileName = SomePath; //RUNTIME EXCEPTION: null reference
What am I missing here?
Note: I'm using Add-in Express.
Got it. I had to cast my application object to Microsoft.Office.Interop.Word.Application to get access to the FileDialog member. The following code works:
var Dlg = ((Microsoft.Office.Interop.Word.Application)Word).get_FileDialog(MsoFileDialogType.msoFileDialogFilePicker);
Dlg.InitialFileName = STRfolderroot + STRfoldertemplatescommon + "\\" + TheModality + "\\" + TheModality + " " + TheStudyType + "\\";
Dlg.Show();
The Microsoft page in your post shows the property being used for the msoFileDialogFilePicker dialog but your code is using the wdDialogFileOpen. The example code on the MS page works fine but trying to use the property for wdDialogFileOpen also generates a run-time error.
So this works:
Sub ThisWorks()
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Dim vrtSelectedItem As Variant
With fd
.InitialFileName = "C:\folder\printer_ink_test.docx"
'If the user presses the action button...
If .Show = -1 Then
For Each vrtSelectedItem In .SelectedItems
MsgBox "Selected item's path: " & vrtSelectedItem
Next vrtSelectedItem
'If the user presses Cancel...
Else
End If
End With
Set fd = Nothing
End Sub
But this fails:
Sub ThisFails()
Dim fd As Dialog
Set fd = Application.Dialogs(wdDialogFileOpen)
Dim vrtSelectedItem As Variant
With fd
' This line causes a run-time error
.InitialFileName = "C:\folder\printer_ink_test.docx"
'If the user presses the action button...
If .Show = -1 Then
For Each vrtSelectedItem In .SelectedItems
MsgBox "Selected item's path: " & vrtSelectedItem
Next vrtSelectedItem
'If the user presses Cancel...
Else
End If
End With
Set fd = Nothing
End Sub
Sorry for screenshot, I'm using my phone to answer.
This is how you do it for Excel according to the picture from google books: Globals.ThisWorkbook.ThisApplication.FileDialog
For MS Word according to this link, this is how its done:
Office.FileDialog dialog = app.get_FileDialog(
Office.MsoFileDialogType.msoFileDialogFilePicker);
//dialog.InitialFileName <-- set initial file name
dialog.Show();
Related
I have recently started experimenting with SQL Server Compact and EF6. I am currently using the model first approach and generating my classes and tables from it. I am curious though, about one thing. How can I get my program to dynamically create the database. It exists on my machine as I created it with the SQL Server Compact/SQLite toolkit, but when the program is deployed to client computers, the database will need to be created.
I would want to prompt them on first run for a good location, then create the entire DB schema and just use that in the future. I looked into this guide but vs started complaining about it not working because I didn't use a code-first approach.
If you need more info let me know! Thanks.
I have a little app I'm working on using SQL CE and EF and I deploy the template database when the app is installed (clickonce). Then I use a spash screen on application start to either load a previously created database or let the user create a new one.
When they create a new db I simply prompt them for a location and copy the template database out to their desired location with their desired name. I've also set it up to use the deployed database without giving them the opportunity have multiple database files.
We are dealing with a few pieces here as follows:
SQL CE database file
My stock/template .sdf file sits in my project folder and is included in the project within Visual Studio (I'm using 2015). Rightclick on the file in the Solution Explorer and select properties you want to set the following:
Build Action - Content
Copy to Output Directory - Copy always
Create global variable
Either use an existing module file or create a new one that looks like this:
Public Module Globals
Friend g_recipeData As RecipeEntities
End Module
Create setting for last file path
Rightclick on your project name in the solution explorer and pick Properties. Click the Settings tab and add a new setting as follows:
Name: lastpath
Type: String
Scope: User
Value:
Create splash screen form (frmSplash)
Mine looks like this:
Controls on the form are as follows:
txtFile
cmdSelectDatabase
cmdNew
cmdOpen
cmdExit
Splash Screen (frmSplash) Code
Region "Form Methods"
Private Sub OnFormLoad() Handles Me.Load
txtFile.Text = My.Settings.lastpath
If txtFile.Text <> "" Then
cmdOpen.Enabled = True
cmdOpen.Select()
Else
cmdNew.Select()
End If
End Sub
Private Sub FileSelect()
Try
Dim openFileDialog As New OpenFileDialog()
openFileDialog.Filter = "sdf files (*.sdf)|*.sdf|All files (*.*)|*.*"
openFileDialog.FilterIndex = 1
openFileDialog.RestoreDirectory = True
Dim result As DialogResult = openFileDialog.ShowDialog(Me)
If result = DialogResult.Cancel Then
cmdSelectDatabase.Select()
Exit Sub
End If
txtFile.Text = openFileDialog.FileName
If txtFile.Text <> "" Then
cmdOpen.Enabled = True
cmdOpen.Select()
My.Settings.lastpath = openFileDialog.FileName
My.Settings.Save()
Else
cmdOpen.Enabled = False
cmdSelectDatabase.Select()
End If
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, "Application Error")
Application.Exit()
Finally
End Try
End Sub
Private Sub SetConnectionString()
Try
Dim providerName As String = "System.Data.SqlServerCe.4.0"
Dim datasource As String = txtFile.Text
Dim sqlCeBuilder As New SqlCeConnectionStringBuilder
sqlCeBuilder.DataSource = datasource
sqlCeBuilder.PersistSecurityInfo = True
g_SQLCeConnectionString = sqlCeBuilder.ConnectionString
Dim providerString As String = sqlCeBuilder.ToString()
Dim entityBuilder As New EntityConnectionStringBuilder()
entityBuilder.Provider = providerName
entityBuilder.ProviderConnectionString = providerString
entityBuilder.Metadata = "res://*/RecipeModel.csdl|res://*/RecipeModel.ssdl|res://*/RecipeModel.msl"
Dim c As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location)
Dim section As ConnectionStringsSection = DirectCast(c.GetSection("connectionStrings"), ConnectionStringsSection)
g_EntityConnectionString = entityBuilder.ConnectionString
section.ConnectionStrings("RecipeEntities").ConnectionString = g_EntityConnectionString
c.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("connectionStrings")
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, "Application Error")
Application.Exit()
End Try
End Sub
Private Sub CreateDatabase()
Try
Dim saveFileDialog As New SaveFileDialog()
saveFileDialog.Filter = "sdf files (*.sdf)|*.sdf"
saveFileDialog.Title = "Create Database"
saveFileDialog.FilterIndex = 1
If saveFileDialog.ShowDialog() = DialogResult.OK Then
File.Copy(Path.Combine(ApplicationDeployment.CurrentDeployment.DataDirectory, "rw.sdf"), saveFileDialog.FileName, True)
Dim strPathandFile As String = saveFileDialog.FileName
txtFile.Text = strPathandFile
My.Settings.lastpath = strPathandFile
My.Settings.Save()
cmdOpen.Enabled = True
End If
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, "Application Error")
Application.Exit()
End Try
End Sub
Private Sub LoadMainApplication()
Try
Dim objNewForm As New FrmMain
objNewForm.Show()
Me.Close()
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, "Application Error")
Application.Exit()
End Try
End Sub
End Region
Region "Event Handlers"
Private Sub cmdSelectDatabase_Click(sender As Object,
e As EventArgs) Handles cmdSelectDatabase.Click
FileSelect()
cmdOpen.Select()
End Sub
Private Sub cmdCancel_Click(sender As Object, e As EventArgs) Handles cmdExit.Click
Me.Close()
End Sub
Private Sub cmdOk_Click(sender As Object, e As EventArgs) Handles cmdOpen.Click
Me.Cursor = Cursors.WaitCursor
SetConnectionString()
LoadMainApplication()
Me.Cursor = Cursors.Default
End Sub
Private Sub txtFile_Validated(sender As Object, e As EventArgs) Handles txtFile.Validated
If txtFile.Text.Length = 0 Then
cmdOpen.Enabled = False
Else
cmdOpen.Enabled = True
End If
End Sub
Private Sub cmdNew_Click(sender As Object,
e As EventArgs) Handles cmdNew.Click
CreateDatabase()
SetConnectionString()
LoadMainApplication()
End Sub
Private Sub CatchEnterKey(ByVal sender As Object,
ByVal e As System.Windows.Forms.KeyPressEventArgs) _
Handles txtFile.KeyPress, txtPassword.KeyPress
If e.KeyChar = ChrW(Keys.Enter) Then
cmdOk_Click(sender, e)
e.Handled = True
Exit Sub
End If
End Sub
Set global variable value
On the form of your main application (frmMain above) add the following to the constructor:
Public Sub New()
InitializeComponent()
g_recipeData = New RecipeEntities
End Sub
If you perform the above action when you create the variable in the module file then the connection string for the entity is set and you can't change it. You must set the connection string in app.config (using the above code) first and then the entity will use desired connection string when instantiated.
I think that's the basics for now. I highly recommend you reading through it again now that I'm done. I made some corrections and even added a step for the lastpath setting. Just hit me up if something isn't working or is confusing and I'll do my best to help. Good luck!
I want to develop an add in Outlook to save the calendars in .ICS format.
I tried this code but it need a class that I should buy :/ !!
' Load the Outlook PST file
Dim pst As PersonalStorage = PersonalStorage.FromFile("d:\Data\Emails\PersonalStorage.pst")
' Get the Calendar folder
Dim folderInfo As FolderInfo = pst.RootFolder.GetSubFolder("Calendar")
' Loop through all the calendar items in this folder
Dim messageInfoCollection As MessageInfoCollection = folderInfo.GetContents()
For Each messageInfo As MessageInfo In messageInfoCollection
' Get the calendar information
Dim calendar As MapiCalendar = CType(pst.ExtractMessage(messageInfo).ToMapiMessageItem(), MapiCalendar)
' Display some contents on screen
Console.WriteLine("Name: " & calendar.Subject)
' Save to disk in ICS format
calendar.Save("Calendar\" & calendar.Subject & ".ics", AppointmentSaveFormat.Ics)
Next messageInfo
Calendars in Outlook are represented by the folders with Outlook items inside. The Folder class provides the GetCalendarExporter method which reates a CalendarSharing object for the specified Folder. Be aware, the GetCalendarExporter method can only be used on calendar folders. An error occurs if you use the method on Folderobjects that represent other folder types.
The CalendarSharing class provides the SaveAsICal method which exports calendar information from the parent Folder of the CalendarSharing object as an iCalendar calendar (.ics) file.
The following VBA example creates a CalendarSharing object for the Calendar folder, then exports the contents of the entire folder (including attachments and private items) to an iCalendar calendar (.ics) file.
Public Sub ExportEntireCalendar()
Dim oNamespace As NameSpace
Dim oFolder As Folder
Dim oCalendarSharing As CalendarSharing
On Error GoTo ErrRoutine
' Get a reference to the Calendar default folder
Set oNamespace = Application.GetNamespace("MAPI")
Set oFolder = oNamespace.GetDefaultFolder(olFolderCalendar)
' Get a CalendarSharing object for the Calendar default folder.
Set oCalendarSharing = oFolder.GetCalendarExporter
' Set the CalendarSharing object to export the contents of
' the entire Calendar folder, including attachments and
' private items, in full detail.
With oCalendarSharing
.CalendarDetail = olFullDetails
.IncludeWholeCalendar = True
.IncludeAttachments = True
.IncludePrivateDetails = True
.RestrictToWorkingHours = False
End With
' Export calendar to an iCalendar calendar (.ics) file.
oCalendarSharing.SaveAsICal "C:\SampleCalendar.ics"
EndRoutine:
On Error GoTo 0
Set oCalendarSharing = Nothing
Set oFolder = Nothing
Set oNamespace = Nothing
Exit Sub
ErrRoutine:
Select Case Err.Number
Case 287 ' &H0000011F
' The user denied access to the Address Book.
' This error occurs if the code is run by an
' untrusted application, and the user chose not to
' allow access.
MsgBox "Access to Outlook was denied by the user.", _
vbOKOnly, _
Err.Number & " - " & Err.Source
Case -2147467259 ' &H80004005
' Export failed.
' This error typically occurs if the CalendarSharing
' method cannot export the calendar information because
' of conflicting property settings.
MsgBox Err.Description, _
vbOKOnly, _
Err.Number & " - " & Err.Source
Case -2147221233 ' &H8004010F
' Operation failed.
' This error typically occurs if the GetCalendarExporter method
' is called on a folder that doesn't contain calendar items.
MsgBox Err.Description, _
vbOKOnly, _
Err.Number & " - " & Err.Source
Case Else
' Any other error that may occur.
MsgBox Err.Description, _
vbOKOnly, _
Err.Number & " - " & Err.Source
End Select
GoTo EndRoutine
End Sub
If you execute backup using SMO, after successful completion, I test the SqlError for null, considering that the backup completed without errors:
But, as you can see, it actually return an error of class 0 number 3014 meaning success.
So the question is:
Q: How can I find out if backup completed successfully or not, and how should I handle these messages and statuses cleanly?
I'm afraid that there are multiple of "gotchas" here that I don't want to bite me in the ass later when this code goes production :)
I agree there are multiple "gotchas" and I personally think Microsoft SMO events are poorly implemented as the ServerMessageEventArgs contains a Property Error which not always provides information about an error but messages about successful operations!!
As an example:
The "error" with code 4035 is an information message. Not an error.
The "error" with code 3014 is an information message that happens when completed successfully. Not an error
Also notice that the Information event does not always happen when an error has occurred. It actually happens whenever SQL Server sends a message that could be information about the operation that has finished successfully
I am also concerned about not handling the errors/success properly, but checking sqlError as Null is a bad idea since it will not be ever null and it will always contain some message about successful operation or an error. And assuming that Information event occurs when there is an error is also a bad idea.
I suggest to handle the errors through the SqlError.Number and depending on the SMO event it has been triggered.
I have made the following code to create a database backup. It is in VB.NET but in C# would be similar. It receives necessary parameters including a delegate where to invoke events (to be handled at GUI), a progress to report the percentage and error handling depending on event triggered and the SqlError.Number as mentioned
Public Sub BackupDatabase(databaseName As String, backupFileFullPath As String, optionsBackup As OptionsBackupDatabase, operationProgress As IProgress(Of Integer),
operationResult As Action(Of OperationResult)) Implements IDatabaseManager.BackupDatabase
Dim sqlBackup As New Smo.Backup()
sqlBackup.Action = Smo.BackupActionType.Database
sqlBackup.BackupSetName = databaseName & " Backup"
sqlBackup.BackupSetDescription = "Full Backup of " & databaseName
sqlBackup.Database = databaseName
Dim bkDevice As New Smo.BackupDeviceItem(backupFileFullPath, Smo.DeviceType.File)
sqlBackup.Devices.Add(bkDevice)
sqlBackup.Initialize = optionsBackup.Overwrite
sqlBackup.Initialize = True
sqlBackup.PercentCompleteNotification = 5
AddHandler sqlBackup.PercentComplete, Sub(sender As Object, e As PercentCompleteEventArgs)
operationProgress.Report(e.Percent)
End Sub
AddHandler sqlBackup.Complete, Sub(sender As Object, e As ServerMessageEventArgs)
Dim sqlMessage As SqlClient.SqlError = e.Error
Dim opResult As New OperationResult()
Select Case sqlMessage.Number
Case 3014
opResult.operationResultType = OperationResultType.SmoSuccess
opResult.message = "Backup successfully created at " & backupFileFullPath & ". " & sqlMessage.Number & ": " & sqlMessage.Message
Case Else
opResult.operationResultType = OperationResultType.SmoError
opResult.message = "ERROR CODE " & sqlMessage.Number & ": " & sqlMessage.Message
End Select
operationResult.Invoke(opResult)
End Sub
AddHandler sqlBackup.NextMedia, Sub(sender As Object, e As ServerMessageEventArgs)
Dim sqlMessage As SqlClient.SqlError = e.Error
Dim opResult As New OperationResult()
opResult.operationResultType = OperationResultType.SmoError
opResult.message = "ERROR CODE: " & sqlMessage.Number & ": " & sqlMessage.Message
operationResult.Invoke(opResult)
End Sub
AddHandler sqlBackup.Information, Sub(sender As Object, e As ServerMessageEventArgs)
Dim sqlMessage As SqlClient.SqlError = e.Error
Dim opResult As New OperationResult()
Select Case sqlMessage.Number
Case 4035
opResult.operationResultType = OperationResultType.SmoInformation
opResult.message = sqlMessage.Number & ": " & sqlMessage.Message
Case Else
opResult.operationResultType = OperationResultType.SmoError
opResult.message = "ERROR CODE " & sqlMessage.Number & ": " & sqlMessage.Message
End Select
operationResult.Invoke(opResult)
End Sub
Try
sqlBackup.SqlBackupAsync(smoServer)
Catch ex As Exception
Throw New BackupManagerException("Error backing up database " & databaseName, ex)
End Try
End Sub
I could be wrong, but I believe that the Complete event firing is the main indicator that the backup was successful - errors would be reported through the Information event.
Since the class of the error is 0 (or any value below 10), it indicates that it's an informational message, not an actual error (Error is somewhat misnamed). And 3014 is defined as the message that's sent when the backup is successful.
I'm not sure what other "gotchas" you're concerned with, since you haven't documented them.
I'm trying to find a way to get mail attachments (programaticaly) , and then open it... can someone tell me how to do this or point me to a right direction?
This is a VBA script (use in a Macro in Outlook) which will loop over all attachments in all selected items in the current folder and Save them to disk.
It should get you started and I don't think it would take much to add some kind of process launch rather than save logic to it.
Public Sub SaveAttachments()
'Note, this assumes you are in the a folder with e-mail messages when you run it.
'It does not have to be the inbox, simply any folder with e-mail messages
Dim Exp As Outlook.Explorer
Dim Sel As Outlook.Selection
Dim AttachmentCnt As Integer
Dim AttTotal As Integer
Dim MsgTotal As Integer
Dim outputDir As String
Dim outputFile As String
Dim fileExists As Boolean
Dim cnt As Integer
'Requires reference to Microsoft Scripting Runtime (SCRRUN.DLL)
Dim fso As FileSystemObject
Set Exp = Application.ActiveExplorer
Set Sel = Exp.Selection
Set fso = New FileSystemObject
outputDir = "C:\Path"
If outputDir = "" Then
MsgBox "You must pick an directory to save your files to. Exiting SaveAttachments.", vbCritical, "SaveAttachments"
Exit Sub
End If
Dim att As Attachment
'Loop thru each selected item in the inbox
For cnt = 1 To Sel.Count
'If the e-mail has attachments...
If Sel.Item(cnt).Attachments.Count > 0 Then
MsgTotal = MsgTotal + 1
'For each attachment on the message...
For AttachmentCnt = 1 To Sel.Item(cnt).Attachments.Count
'Get the attachment
Set att = Sel.Item(cnt).Attachments.Item(AttachmentCnt)
outputFile = att.FileName
outputFile = Format(Sel.Item(cnt).ReceivedTime, "yyyy-mm-dd_hhmmss - ") + outputFile
fileExists = fso.fileExists(outputDir + outputFile)
'Save it to disk if the file does not exist
If fileExists = False Then
att.SaveAsFile (outputDir + outputFile)
AttTotal = AttTotal + 1
End If
Set att = Nothing
Sel.Item(cnt).Close (Outlook.OlInspectorClose.olDiscard)
Next
End If
Next
'Clean up
Set Sel = Nothing
Set Exp = Nothing
Set fso = Nothing
'Let user know we are done
Dim doneMsg As String
doneMsg = "Completed saving " + Format$(AttTotal, "#,0") + " attachments in " + Format$(MsgTotal, "#,0") + " Messages."
MsgBox doneMsg, vbOKOnly, "Save Attachments"
Exit Sub
ErrorHandler:
Dim errMsg As String
errMsg = "An error has occurred. Error " + Err.Number + " " + Err.Description
Dim errResult As VbMsgBoxResult
errResult = MsgBox(errMsg, vbAbortRetryIgnore, "Error in Save Attachments")
Select Case errResult
Case vbAbort
Exit Sub
Case vbRetry
Resume
Case vbIgnore
Resume Next
End Select
End Sub
Look for the COM-reference of Outlook.
You can also use a macro written in vba to do this.
Is there any way to set a custom Icon of an Outlook folder or subfolder using Outlook object model?
As from Outlook 2010 you can use MAPIFolder.SetCUstomIcon as described above.
I have had the same challenge recently and found a nice snippet of VBA code at
Change Outlook folders colors possible?:
joelandre Jan 12, 2015 at 9:13 PM
Unzip the file icons.zip to C:\icons
Define the code below as Visual Basic Macros
Adapt the function ColorizeOutlookFolders according to your needs Text
Function GetFolder(ByVal FolderPath As String) As Outlook.folder
' Returns an Outlook folder object basing on the folder path
'
Dim TempFolder As Outlook.folder
Dim FoldersArray As Variant
Dim i As Integer
On Error GoTo GetFolder_Error
'Remove Leading slashes in the folder path
If Left(FolderPath, 2) = "\\" Then
FolderPath = Right(FolderPath, Len(FolderPath) - 2)
End If
'Convert folderpath to array
FoldersArray = Split(FolderPath, "\")
Set TempFolder = Application.Session.Folders.Item(FoldersArray(0))
If Not TempFolder Is Nothing Then
For i = 1 To UBound(FoldersArray, 1)
Dim SubFolders As Outlook.Folders
Set SubFolders = TempFolder.Folders
Set TempFolder = SubFolders.Item(FoldersArray(i))
If TempFolder Is Nothing Then
Set GetFolder = Nothing
End If
Next
End If
'Return the TempFolder
Set GetFolder = TempFolder
Exit Function GetFolder_Error:
Set GetFolder = Nothing
Exit Function End Function Sub ColorizeOneFolder(FolderPath As String, FolderColour As String)
Dim myPic As IPictureDisp
Dim folder As Outlook.folder
Set folder = GetFolder(FolderPath)
Set myPic = LoadPicture("C:\icons\" + FolderColour + ".ico")
If Not (folder Is Nothing) Then
' set a custom icon to the folder
folder.SetCustomIcon myPic
'Debug.Print "setting colour to " + FolderPath + " as " + FolderColour
End If End Sub
Sub ColorizeFolderAndSubFolders(strFolderPath As String, strFolderColour As String)
' this procedure colorizes the foler given by strFolderPath and all subfolfers
Dim olProjectRootFolder As Outlook.folder
Set olProjectRootFolder = GetFolder(strFolderPath)
Dim i As Long
Dim olNewFolder As Outlook.MAPIFolder
Dim olTempFolder As Outlook.MAPIFolder
Dim strTempFolderPath As String
' colorize folder
Call ColorizeOneFolder(strFolderPath, strFolderColour)
' Loop through the items in the current folder.
For i = olProjectRootFolder.Folders.Count To 1 Step -1
Set olTempFolder = olProjectRootFolder.Folders(i)
strTempFolderPath = olTempFolder.FolderPath
'prints the folder path and name in the VB Editor's Immediate window
'Debug.Print sTempFolderPath
' colorize folder
Call ColorizeOneFolder(strTempFolderPath, strFolderColour)
Next
For Each olNewFolder In olProjectRootFolder.Folders
' recursive call
'Debug.Print olNewFolder.FolderPath
Call ColorizeFolderAndSubFolders(olNewFolder.FolderPath, strFolderColour)
Next
End Sub
Sub ColorizeOutlookFolders()
Call ColorizeFolderAndSubFolders("\\Personal\Documents\000-Mgmt-CH\100-People", "blue")
Call ColorizeFolderAndSubFolders("\\Personal\Documents\000-Mgmt-CH\200-Projects","red")
Call ColorizeFolderAndSubFolders("\\Personal\Documents\000-Mgmt-CH\500-Meeting", "green")
Call ColorizeFolderAndSubFolders("\\Personal\Documents\000-Mgmt-CH\800-Product", "magenta")
Call ColorizeFolderAndSubFolders("\\Personal\Documents\000-Mgmt-CH\600-Departments", "grey")
Call ColorizeFolderAndSubFolders("\\Mailbox - Dan Wilson\Inbox\Customers", "grey")
End Sub
In the object ThisOutlookSession, define the following function:
Private Sub Application_Startup()
ColorizeOutlookFolders
End Sub
and
In order to NOT color sub-folders, you can use the function
ColorizeOneFolder instead of ColorizeFolderAndSubFolders e.g.
Sub ColorizeOutlookFolders()
Call ColorizeOneFolder ("\\Personal\Documents\000-Mgmt-CH\100-People", "blue")
Call ColorizeOneFolder ("\\Personal\Documents\000-Mgmt-CH\200-Projects", "red")
Call ColorizeOneFolder ("\\Personal\Documents\000-Mgmt-CH\500-Meeting", "green")
Call ColorizeOneFolder ("\\Personal\Documents\000-Mgmt-CH\800-Product", "magenta")
Call ColorizeOneFolder ("\\Personal\Documents\000-Mgmt-CH\600-Departments", "grey")
Call ColorizeOneFolder ("\\Mailbox - Dan Wilson\Inbox\Customers", "grey")
End Sub
When you move sub-folders between folders, they should retain their
color only until the next time you restart Outlook.
From what I have read this is unfortunately not possible in Outlook 2007.
It is possible in Outlook 2010 using MAPIFolder.SetCustomIcon. See MSDN for more details: http://msdn.microsoft.com/en-us/library/ff184775.aspx
Switching the list of MAPIFolder methods between 2010 and 2007 on the following MSDN webpage shows the SetCustomIcon method for 2010 only: http://msdn.microsoft.com/en-us/library/bb645002.aspx