Delete duplicate mails Outlook 2013 - vba

Im trying to create a VBA macro that checks if there is a duplicate mail (looks at subject) and then deletes the mail.
This code works but is deleting the oldest duplicates. It's counting in descending order and I can't seem to get the sorting of the items to work.
Basically I need help figuring out how to make sure the "newest" duplicate by received time gets deleted.
Sub RemoveDuplicates()
Dim oFolder As Folder
Dim oEmail As MailItem, oItems As ItemProperties, oItem As ItemProperty
Dim cMail As Collection
Dim i As Long
Set oFolder = Application.ActiveExplorer.CurrentFolder
Set cMail = New Collection
With oFolder
' .Items.Sort "[ReceivedTime]", True
If olMailItem <> .DefaultItemType Then Exit Sub
For i = .Items.Count To 1 Step -1
Set oItems = .Items(i).ItemProperties
Debug.Print oItems("ReceivedTime")
If Not oItems("ReceivedTime") Is Nothing Then
Set oItem = oItems("ReceivedTime")
'// Week old
If oItem >= Date - 7 Then
On Error GoTo ErrHandler
'// Delete Duplicate Subject
cMail.Add oItems("Subject"), oItems("Subject")
On Error GoTo 0
End If
End If
Next i
End With
Exit Sub
ErrHandler:
Debug.Print Err.Number, oItems("Subject"), oItems("ReceivedTime")
oFolder.Items(i).Delete
Resume Next
End Sub

Cache the Items collection before entering the loop (otherwise you get a brand new Items COM object each time), sort it on ReceivedTime (Items.Sort), then loop from Count down to 1.

Expanding on #DmitryStreblechenko's answer:
The following will keep the MailItem with the oldest date and delete more recent ones with the same subject.
For convenience TargetFolder and MinDate are configurable but optional. They default to the currently visible folder and seven days ago.
Sub RemoveDuplicates(Optional TargetFolder As Folder, Optional MinDate As Date)
Dim Items As Items, Email As MailItem
Dim i As Long, Dupes As Object
If MinDate = vbEmpty Then MinDate = Date - 7
If TargetFolder Is Nothing Then Set TargetFolder = ActiveExplorer.CurrentFolder
Set Dupes = CreateObject("Scripting.Dictionary")
Set Items = TargetFolder.Items
Items.Sort "[ReceivedTime]"
Debug.Print "Dedupe <" & TargetFolder.FolderPath & ">, " & Items.Count & " items"
For i = Items.Count To 1 Step -1
If TypeOf Items(i) Is MailItem Then
Set Email = Items(i)
If Email.ReceivedTime >= MinDate Then
If Dupes.Exists(Email.Subject) Then
Debug.Print "DELETE: " & Email.Subject
'Item.Delete
Else
Dupes.Add Email.Subject, 0
End If
End If
End If
Next i
End Sub
This makes use of a Scripting.Dictionary because unlike the Collection object it supports a handy Exists() method.

Related

How to set focus to Inbox?

When you open Outlook, Inbox has the focus. If you go to another folder then run VBA code the focus stays on that folder.
My macro deletes all files in my Deleted folder and Trash folder. I would like it to come back to the Inbox when complete.
Public Sub EmptyFolder()
Dim Items As Outlook.Items
Dim i As Long
Dim Count As Long
Dim Delete As Boolean
' Clear Junk Items
Set ns = Application.GetNamespace("MAPI")
Set Items = Session.GetDefaultFolder(olFolderCalendar).Parent.Folders("Junk").Items
Count = Items.Count
If Count = 0 Then
GoTo DeleteAll
End If
Delete = True
For i = Count To 1 Step -1
Items(i).Delete
Next
DeleteAll:
' Clear Trash Items
Set Items = Session.GetDefaultFolder(olFolderCalendar).Parent.Folders("Trash").Items
Count = Items.Count
If Count = 0 Then
GoTo EndAll
End If
Delete = True
For i = Count To 1 Step -1
Items(i).Delete
Next
EndAll:
End Sub
You could just change the CurrentFolder value to one of your Inbox folders in my example "family" as follow.
Sub ChangeCurrentFolder()
Dim myNamespace As Outlook.NameSpace
Set ns = Application.GetNamespace("MAPI")
Set Application.ActiveExplorer.CurrentFolder = ns.GetDefaultFolder(olFolderInbox)
End Sub
On a related note to what you are trying to achieve (but not directly related to the question), I use a generic function to delete older e-mails from folders and the code is below:
Call the function in Startup
In ThisOutlookSession
Private Sub Application_Startup()
On Error Resume Next
Call DeleteAgedJunkMail
End Sub
In a module
Function DeleteAgedJunkMail() As Boolean
Dim ThisNamespace As Outlook.NameSpace: Set ThisNamespace = Application.GetNamespace("MAPI")
Dim Inbox As Outlook.MAPIFolder: Set Inbox = ThisNamespace.GetDefaultFolder(olFolderInbox)
Dim Junk As Outlook.MAPIFolder: Set Junk = ThisNamespace.GetDefaultFolder(olFolderJunk)
On Error Resume Next
Call DeleteAgedMail(Junk, 7)
Call DeleteAgedMail(Inbox.Folders("Quotes"), 90)
Call DeleteAgedMail(Inbox.Folders("Orders"), 90)
DeleteAgedJunkMail = True
End Function
Function DeleteAgedMail(ByRef Folder As Outlook.MAPIFolder, Optional Days As Long = 7) As Boolean
On Error GoTo ExitFunction
Dim Var As Variant, i As Long, Difference As Long, Items As Long
For i = Folder.Items.Count To 1 Step -1
Set Var = Folder.Items.Item(i)
DoEvents
If Var.Class = olMail Then
Difference = DateDiff("d", Var.SentOn, Now)
If Difference > Days Then
Var.Delete
Items = Items + 1 'Count the # of items deleted
End If
End If
Next
' Record the number of items that were deleted.
Debug.Print "Deleted " & Items & " message(s) from '" & Folder.Name & "'."
DeleteAgedMail = True
ExitFunction:
End Function

Targeting specific Outlook Mail folder

I am trying to create an Outlook Macro that will analyze the subject of an Inbox folder and decide where to move them to a subfolder or delete them based on a list of keywords for four different categories.
The problem is that the Inbox I am using is not the regular Inbox (I have two different Inbox folders, and this one is not the default one). So I need to target it in a way similar to writing the full path (Example: "\\xxx#xxx.net\Inbox\"). I tried to find an answer to it but all the info I found here relates to the assumption that we are working from the default Inbox.
Sub CountAttachmentsMulti2()
Dim oItem As Object
Dim iAttachments As Integer
For Each oItem In ActiveExplorer.Selection
iAttachments = oItem.Attachments.Count + iAttachments
If oItem.Attachments.Count <> 0 Then 'Si el mensaje contiene adjuntos
NumofItems = oItem.Attachments.Count + NumofItems
For j = 1 To oItem.Attachments.Count
MsgBox oItem.Attachments.Item(j).DisplayName
Value = oItem.Attachments.Item(j).DisplayName
If InStr(LCase(Value), "su") > 0 Then
MsgBox "Clap"
End If
Next j
Else
MsgBox oItem.Subject 'Get Subject Title
NumofItems = NumofItems + 1
End If
Next
MsgBox "Selected " & ActiveExplorer.Selection.Count & " messages with " & iAttachments & " attachements"
MsgBox "# of items = " & NumofItems
End Sub
This is the code I have tried initially, because before they have already separated by categories. So all that required is to count the total e-mails either by subject or number of attachments.
My issue right now is that I do not know how to target this e-mail account by using a full path.
If I know how to target that folder I think I can solve the rest of the problem myself.
After following the "possible-duplicate" link I was able to complete my code. I apologize because I did not know it was called a reference. Here is my complete solution to the issue:
Sub Test()
Dim objNS As Outlook.NameSpace
Dim objFolder As Outlook.MAPIFolder
Dim Target_Folder As Outlook.MAPIFolder
Dim oItem As Object
Dim iAttachments As Integer
Set objNS = GetNamespace("MAPI")
Set objFolder_root = objNS.Folders("Testing") 'Getting Outlook Container
Set objFolder = objFolder_root.Folders("Inbox") 'Target Inbox of the other container
For Loops = objFolder.Items.Count To 1 Step -1
Set oItem = objFolder.Items(Loops)
If Category1(oItem.Subject) Then
'MsgBox "Clap1"
Set Target_Folder = objFolder_root.Folders("Category 1")
oItem.Move Target_Folder
ElseIf Category2(oItem.Subject) Then
'MsgBox "Clap2"
Set Target_Folder = objFolder_root.Folders("Category 2")
oItem.Move Target_Folder
ElseIf Category3(oItem.Subject) Then
'MsgBox "Clap3"
Set Target_Folder = objFolder_root.Folders("Category 3")
oItem.Move Target_Folder
ElseIf Category4(oItem.Subject) Then
'MsgBox "Clap4"
Set Target_Folder = objFolder_root.Folders("Category 4")
oItem.Move Target_Folder
Else
MsgBox oItem.Subject & " does not belong to any of the 4 categories"
End If
Next
End Sub
Function Category1(value)
Category_1_Keywords = Array("a")
For i = 0 To UBound(Category_1_Keywords)
If InStr(LCase(value), Category_1_Keywords(i)) > 0 Then
Category1 = True
Exit Function
Else
Category1 = False
End If
Next
End Function
There are, of course, more functions, I just posted the Category1 as a reference

Delete email from inbox and also delete it from deleted-items folder via rule->script

I created a rule, that starts a VBA-script depending on the subject of a received email (Rule: Subject "MY_SUBJECT" -> start script).
The VBA script is then doing some stuff and then it should finally delete the original email.
This part is easy:
Sub doWorkAndDeleteMail(Item As Outlook.MailItem)
' doSomething:
' delete email from inbox
Item.Delete
End Sub
Now the email will sit in the deleted-items-folder. But what I need to achieve is, to also delete this mail from the deleted-items folder. Since I know the subject of this mail (because this triggered my rule in the first place), I tried the following approach:
Sub doWorkAndDeleteMail(Item As Outlook.MailItem)
' doSomething:
' delete email from inbox
Item.Delete
End Sub
' delete email from deleted items-folder
Dim deletedFolder As Outlook.Folder
Set deletedFolder = Application.GetNamespace("MAPI"). _
GetDefaultFolder(olFolderDeletedItems)
Dim i As Long
For i = myFolder.Items.Count To 1 Step -1
If (deletedFolder.Items(i).Subject) = "MY_SUBJECT" Then
deletedFolder.Items(i).Delete
Exit For
End If
Next if
End Sub
Well, this basically works: The mail with this subject will be found in the deleted-items-folder and it will be deleted, yes.
But sadly it does not work as expected:
This permanent deletion only works once I start the script a second time.
So the email which is triggering my script will never be deleted permanently in this script's actual run, but only in the next run (once the next email with the trigger-subject for my rule is received - but then this very next email won't be deleted, again).
Do you have any idea what I am doing wrong here? It somehow looks like I need to refresh my deleted-items folder somehow. Or do I have to comit my first Item.Delete somehow explicitly?
The problem was not recreated, but try stepping through this then run normally if it appears to do what you want.
Sub doWorkAndDeleteMail(Item As mailitem)
Dim currFolder As Folder
Dim DeletedFolder As Folder
Dim i As Long
Dim mySubject As String
Set currFolder = ActiveExplorer.CurrentFolder
mySubject = Item.Subject
Debug.Print mySubject
Set DeletedFolder = GetNamespace("MAPI").GetDefaultFolder(olFolderDeletedItems)
Set ActiveExplorer.CurrentFolder = DeletedFolder
Debug.Print "DeletedFolder.count before delete: " & DeletedFolder.Items.count
' delete email from deleted items-folder
Item.Delete
Debug.Print "DeletedFolder.count after delete: " & DeletedFolder.Items.count
' If necessary
'DoEvents
For i = DeletedFolder.Items.count To 1 Step -1
Debug.Print DeletedFolder.Items(i).Subject
If (DeletedFolder.Items(i).Subject) = mySubject Then
Debug.Print DeletedFolder.Items(i).Subject & " *** found ***"
DeletedFolder.Items(i).Delete
Exit For
End If
Next
Set ActiveExplorer.CurrentFolder = currFolder
End Sub
Tim Williams suggested another existing thread. I had a look at that already before and decided that appoach would be exactly the same representation of my bug. I did try it out, though (to show my motiviation :) ), but the behaviour is - as expected - exactly the same: Again the final deletion only works once the next time the script is triggered via rule:
Sub doWorkAndDeleteMail(Item As Outlook.MailItem)
' First set a property to find it again later
Item.UserProperties.Add "Deleted", olText
Item.Save
Item.Delete
'Now go through the deleted folder, search for the property and delete item
Dim objDeletedFolder As Outlook.Folder
Dim objItem As Object
Dim objProperty As Variant
Set objDeletedFolder = Application.GetNamespace("MAPI"). _
GetDefaultFolder(olFolderDeletedItems)
For Each objItem In objDeletedFolder.Items
Set objProperty = objItem.UserProperties.Find("Deleted")
If TypeName(objProperty) <> "Nothing" Then
objItem.Delete
End If
Next
End Sub
I would be really glad to get some help here. I also wanted to comment on that other thread, but my reputation is not enough, yet.
Try something like this, code goes under ThisOutlookSession
Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
Dim olNs As Outlook.NameSpace
Dim DeletedFolder As Outlook.MAPIFolder
Set olNs = Application.GetNamespace("MAPI")
Set DeletedFolder = olNs.GetDefaultFolder(olFolderDeletedItems)
Set Items = DeletedFolder.Items
End Sub
Private Sub Items_ItemAdd(ByVal Item As Object)
Dim olNs As Outlook.NameSpace
Dim DeletedFolder As Outlook.MAPIFolder
Dim Items As Outlook.Items
Dim Filter As String
Dim i As Long
Set olNs = Application.GetNamespace("MAPI")
Set DeletedFolder = olNs.GetDefaultFolder(olFolderDeletedItems)
Filter = "[Subject] = 'MY_SUBJECT'"
Set Items = DeletedFolder.Items.Restrict(Filter)
If TypeOf Item Is Outlook.MailItem Then
For i = Items.Count To 1 Step -1
DoEvents
Items.Remove i
Next
End If
End Sub
Edit
Sub doWorkAndDeleteMail(Item As Outlook.MailItem)
' First set a property to find it again later
Item.UserProperties.Add "Deleted", olText
Item.Save
Item.Delete
'Now go through the deleted folder, search for the property and delete item
Dim olNs As Outlook.NameSpace
Dim DeletedFolder As Outlook.MAPIFolder
Dim Items As Outlook.Items
Dim Filter As String
Dim i As Long
Set olNs = Application.GetNamespace("MAPI")
Set DeletedFolder = olNs.GetDefaultFolder(olFolderDeletedItems)
Filter = "[Subject] = 'MY_SUBJECT'"
Set Items = DeletedFolder.Items.Restrict(Filter)
If TypeOf Item Is Outlook.MailItem Then
For i = Items.Count To 1 Step -1
DoEvents
Items.Remove i
Next
End If
End Sub
the Mailbox folder that you get can be used as a collection, meaning that you can remove the item directly, you will need the collection to be sent to the function but that should be managable :)
Sub doWorkAndDeleteMail(Mailbox As Outlook.Folder, Item As Outlook.MailItem)
' doSomething:
' delete email from inbox
For Ite = 1 To Mailbox.Items.Count
If Mailbox.Items(Ite).EntryID = Item.EntryID Then
Mailbox.Items.Remove Ite
Exit For
End If
Next
End Sub
Remember that IF you want to Delete more than 1 Item per call of "For Ite = 1 To Mailbox.Items.Count", you will need to subtract 1 from the check of the item within the For segment since when you remove a mail from it, it will reduce the rest of the mails index number by 1.
Hope you can still use this :)
Regards Sir Rolin

How do I create a macro to move the oldest 20 emails from the bottom of my inbox to another folder in outlook?

I'm trying to move the bottom 20 emails to another folder in Outlook to another folder where the macro runs. I'm able to move then when selected but I don't want to have to select 20 from the bottom (oldest) first. I'd like to automate this bit too.
Any help would be appreciated.
Here's what I have so far but it moves the most recent mail only, regardless of how the inbox is sorted:
Public Sub Move_Inbox_Emails()
Dim outApp As Object
Dim outNS As Object
Dim inboxFolder As Object
Dim destFolder As Object
Dim outEmail As Object
Dim inboxItems As Object
Dim i As Integer
Dim inputNumber As String
Dim numberToMove As Integer
inputNumber = InputBox("Enter number of emails to move")
On Error Resume Next
numberToMove = CInt(inputNumber)
On Error GoTo 0
If numberToMove < 1 Then Exit Sub
Set outApp = CreateObject("Outlook.Application")
Set outNS = outApp.GetNamespace("MAPI")
Set inboxFolder = outNS.GetDefaultFolder(olFolderInbox)
Set destFolder = inboxFolder.Parent.Folders("Mobus") 'Test folder at same level as Inbox
'Sort Inbox items by Received Time
Set itemsCol = inboxFolder.Items
itemsCol.Sort "[ReceivedTime]", False
'Loop through sorted items for the number entered by the user, up to the number of items in the Inbox
For i = inboxFolder.Items.Count To inboxFolder.Items.Count - numberToMove + 1 Step -1
If inboxFolder.Items(i).Class = OlObjectClass.olMail Then
Set outEmail = inboxFolder.Items(i)
'Debug.Print outEmail.ReceivedTime, outEmail.subject
outEmail.Move destFolder
End If
Next
End Sub
I've solved this now with some ideas from the commentors, thanks very much. This code now prompts for how many to move and takes them from the oldest first:
Public Sub Move_Inbox_Emails_From_Excel()
Dim outApp As Object
Dim outNS As Object
Dim inboxFolder As Object
Dim destFolder As Object
Dim outEmail As Object
Dim inboxItems As Object
Dim i As Integer
Dim inputNumber As String
Dim numberToMove As Integer
inputNumber = InputBox("Enter number of emails to move")
On Error Resume Next
numberToMove = CInt(inputNumber)
On Error GoTo 0
If numberToMove < 1 Then Exit Sub
Set outApp = CreateObject("Outlook.Application")
Set outNS = outApp.GetNamespace("MAPI")
Set inboxFolder = outNS.GetDefaultFolder(olFolderInbox)
Set destFolder = inboxFolder.Parent.Folders("Mobus") 'Test folder at same level as Inbox
'Sort Inbox items by Received Time
Set inboxItems = inboxFolder.Items
'inboxItems.Sort "[ReceivedTime]", False 'ascending order (oldest first)
inboxItems.Sort "[ReceivedTime]", True 'descending order (newest first)
'Loop through sorted items for the number entered by the user, up to the number of items in the Inbox
For i = inboxFolder.Items.Count To inboxFolder.Items.Count - numberToMove + 1 Step -1
Set outEmail = inboxItems(i)
'Debug.Print i, outEmail.Subject
outEmail.Move destFolder
Next
End Sub
Sort the Items collection by ReceivedTime property, loop though the last 20 items (use a down loop - step -1) and move the items.

Check e-mails in specific time frame

I need to check items in a folder in a specific time frame.
My code goes through all the mails in the specified folder, but the folder has thousands of mails, so it takes forever.
How do I check the mails only from, for example, 3/16/2015 12:00PM to 3/16/2015 2:00PM?
This is what I have:
Sub ExportToExcel()
Dim appExcel As Excel.Application
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Dim rng As Excel.Range
Dim workbookFile As String
Dim msg As Outlook.MailItem
Dim nms As Outlook.NameSpace
Dim fld As Outlook.MAPIFolder
Dim itm As Object
'Folder path and file name of an existing Excel workbook
workbookFile = "C:\Users\OutlookItems.xls"
'Select export folder
Set nms = Application.GetNamespace("MAPI")
Set fld = nms.PickFolder
'Handle potential errors with Select Folder dialog box.
If fld Is Nothing Then
MsgBox "There are no mail messages to export", vbOKOnly, _
"Error"
Exit Sub
ElseIf fld.DefaultItemType <> olMailItem Then
MsgBox "There are no mail messages to export", vbOKOnly, _
"Error"
Exit Sub
ElseIf fld.Items.Count = 0 Then
MsgBox "There are no mail messages to export", vbOKOnly, _
"Error"
Exit Sub
End If
' Open and activate Excel workbook.
Set appExcel = CreateObject("Excel.Application")
Set wkb = appExcel.Workbooks.Open(workbookFile)
Set wks = wkb.Sheets(1)
wks.Activate
appExcel.Application.Visible = True
Set rng = wks.Range("A1")
'Copy field items in mail folder.
For Each itm In fld.Items
If itm.Class = Outlook.OlObjectClass.olMail Then
Set msg = itm
If InStr(msg.Subject, "Error in WU_Send") > 0 And DateDiff("h", msg.SentOn, Now) <= 2 Then
rng.Offset(0, 4).Value = msg.Body
Set rng = rng.Offset(1, 0)
End If
End If
Next
End Sub
The problem lies in this part:
For Each itm In fld.Items
If itm.Class = Outlook.OlObjectClass.olMail Then
Set msg = itm
If InStr(msg.Subject, "Error in WU_Send") > 0 And DateDiff("h", msg.SentOn, Now) <= 2 Then
How do I look at e-mails between specified hours?
You need to use the Find/FindNext or Restrict methods of the Items class instead of iterating through all items in the folder. For example:
Sub DemoFindNext()
Dim myNameSpace As Outlook.NameSpace
Dim tdystart As Date
Dim tdyend As Date
Dim myAppointments As Outlook.Items
Dim currentAppointment As Outlook.AppointmentItem
Set myNameSpace = Application.GetNamespace("MAPI")
tdystart = VBA.Format(Now, "Short Date")
tdyend = VBA.Format(Now + 1, "Short Date")
Set myAppointments = myNameSpace.GetDefaultFolder(olFolderCalendar).Items
Set currentAppointment = myAppointments.Find("[Start] >= """ & tdystart & """ and [Start] <= """ & tdyend & """")
While TypeName(currentAppointment) <> "Nothing"
MsgBox currentAppointment.Subject
Set currentAppointment = myAppointments.FindNext
Wend
End Sub
See the following articles for more information and sample code:
How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)
How To: Use Restrict method to retrieve Outlook mail items from a folder
Also you may find the AdvancedSearch method of the Application class helpful. The key benefits of using the AdvancedSearch method are listed below:
The search is performed in another thread. You don’t need to run another thread manually since the AdvancedSearch method runs it automatically in the background.
Possibility to search for any item types: mail, appointment, calendar, notes etc. in any location, i.e. beyond the scope of a certain folder. The Restrict and Find/FindNext methods can be applied to a particular Items collection (see the Items property of the Folder class in Outlook).
Full support for DASL queries (custom properties can be used for searching too). You can read more about this in the Filtering article in MSDN. To improve the search performance, Instant Search keywords can be used if Instant Search is enabled for the store (see the IsInstantSearchEnabled property of the Store class).
You can stop the search process at any moment using the Stop method of the Search class.
You could just change the line to:
If InStr(msg.Subject, "Error in WU_Send") > 0 And msg.SentOn > "03/16/2015 12:00 PM" AND msg.SentOn < "03/16/2015 2:00 PM" Then
This specifies the time period.
Option Explicit
Sub RestrictTimePeriod()
Dim nms As Namespace
Dim fld As folder ' Subsequent to 2003 otherwise MAPIFolder
Dim msg As MailItem
Dim filterCriteria As String
Dim filterItems As Items
Dim i As Long
Dim start
Dim dif
Set nms = Application.GetNamespace("MAPI")
Set fld = nms.PickFolder
If Not fld Is Nothing Then
start = Now
Debug.Print start
' http://www.jpsoftwaretech.com/use-filters-to-speed-up-outlook-macros/
filterCriteria = "[ReceivedTime] > " & QuoteWrap("2015-03-16 12:00 PM") & _
" And [ReceivedTime] < " & QuoteWrap("2015-03-17 2:00 PM")
Set filterItems = fld.Items.Restrict(filterCriteria)
For i = filterItems.count To 1 Step -1
Set msg = filterItems.Item(i)
Debug.Print msg.Subject
Next
End If
ExitRoutine:
Set nms = Nothing
Set msg = Nothing
Set filterItems = Nothing
Debug.Print Now
dif = (Now - start) * 86400
Debug.Print dif
Debug.Print "Done."
End Sub
Function QuoteWrap(stringToWrap As String, _
Optional charToUse As Long = 39) As String
' http://www.jpsoftwaretech.com/use-filters-to-speed-up-outlook-macros/
' use 34 for double quotes, 39 for apostrophe
QuoteWrap = Chr(charToUse) & stringToWrap & Chr(charToUse)
End Function