Encrypting a string with VBA

cecil
StarLounger
Posts: 98
Joined: 09 Sep 2010, 16:01

Encrypting a string with VBA

Post by cecil »

I would like to encrypt a string using VBA. Can someone give me some pointers? I am using Excel 2007 for this.

Thanks

User avatar
HansV
Administrator
Posts: 78549
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Encrypting a string with VBA

Post by HansV »

I have attached a text file with the code for a class module that calls the Cryptographic Service Provider built into Windows. There is no need to understand the code (I don't understand it either).
In the VB Editor, select Insert | Class Module, then copy the contents of the text file into the module.
EncryptClass.txt
Here is an example of how you can use the class module to encrypt a string:

Code: Select all

Sub EncryptExample()
    Dim strSource As String
    Dim strTarget As String
    Dim strPassword As String
    ' Create instance of class module
    Dim cls As New clsEncrypt
    ' Set encryption password.
    cls.Password = "topsecret"
    strSource = "Eileen's Lounge"
    cls.InBuffer = strSource
    cls.Encrypt
    strTarget = cls.OutBuffer
    Debug.Print strTarget
    Set cls = Nothing
End Sub
You do not have the required permissions to view the files attached to this post.
Best wishes,
Hans

cecil
StarLounger
Posts: 98
Joined: 09 Sep 2010, 16:01

Re: Encrypting a string with VBA

Post by cecil »

It worked well. Thanks Hans

I tried to see if it would handle special characters. I used all the special characters on the top row of the keyboard. !@#$%^&*()_+ That gave me some wierd results, which I could not decript. However, when I tried these characters in another string, they all worked fine. Note: I decrypted by copying the encrypted string and pasting it. If I had read from a file, it may have worked.

Thanks again.

User avatar
HansV
Administrator
Posts: 78549
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Encrypting a string with VBA

Post by HansV »

The encrypted string may contain line feed characters, which makes it more complicated to handle it.
Best wishes,
Hans