PDA

View Full Version : [SOLVED:] Outlook VBA Persistent Variable



Student7
03-14-2015, 12:18 PM
I'm looking for a way to store a short text string using VBA that will later be read by VBA and will not be lost when Outlook is closed. I know that VBA itself does not provide any way to do this, but I'm thinking there must be some way to do it, like setting some hidden Outlook property that does not get lost.

I thought I was on to something by creating a UserDefinedProperties Item on the MAPI Inbox, but then I found out that doing so only defines the property and you can only set the actual value of the property on the mail items in the folder. I chose Inbox because it's common to all MAPI mailboxes and will never be deleted.

Any ideas along these lines or any other way to do this?

skatonni
03-14-2015, 06:18 PM
You can store the string in a file as described by VBOffice.

http://www.vboffice.net/en/developers/open-and-save-files


Public Function ReadFile(sPath As String) As String
' http://www.vboffice.net/en/developers/open-and-save-files
On Error GoTo AUSGANG
Dim lFileNr As Long
Dim sText As String

lFileNr = FreeFile

Open sPath For Binary As #lFileNr
sText = Space$(LOF(lFileNr))
Get #lFileNr, , sText

AUSGANG:
If lFileNr Then Close #lFileNr
If Err.Number Then Err.Raise Err.Number, Err.Source, Err.Description
ReadFile = sText
End Function

Public Sub WriteFile(sPath As String, _
sText As String, _
Optional ByVal bAppend As Boolean _
)
On Error GoTo AUSGANG
Dim lFileNr As Long

lFileNr = FreeFile

Select Case bAppend
Case False
Open sPath For Output As #lFileNr
Case Else
Open sPath For Append As #lFileNr
End Select
Print #lFileNr, sText;

AUSGANG:
If lFileNr Then Close #lFileNr
If Err.Number Then Err.Raise Err.Number, Err.Source, Err.Description
End Sub

Not specific to the question. Example usage, to generate consecutive numbers.

http://www.vboffice.net/en/developers/create-a-serial-number/?mnu=2&cmd=showitem


Public Function GetNextID() As Long
' http://www.vboffice.net/en/developers/create-a-serial-number/?mnu=2&cmd=showitem
Dim lCurrID As Long
Dim File As String

File = "C:Sample.txt"
lCurrID = Val(ReadFile(File))
lCurrID = lCurrID + 1
WriteFile (http://www.vboffice.net/en/developers/open-and-save-files) File, CStr(lCurrID), False
GetNextID = lCurrID
End Function

Student7
03-15-2015, 02:35 PM
Thanks skatonni for the reply. This solution can work but I failed to mention that I was looking for a way to do it without using an external file.

This post made me think about it a different way and realize I'm already using an external file that I can use store my persistent data. My VBA uses an .oft template saved in a folder on C:\ and I can store my data right in the template and then delete it out before sending the email. My data could go in the body of the email, but I think I'm going to use the mailitem.companies property to store the string. Thanks.