VBA Code explantion

sauce1979

New member
Local time
Yesterday, 16:37
Joined
Aug 7, 2008
Messages
3
Hi there. I have jsut joined this forum and would like an explanation for a tutorial I amd doing from an VBA programming book. The code below is the code for two command buttons on a simple encryption applicaiton. My area of concern are the lines (in bold) in both button click events. When the chr function is used to convert a character code back to a character -1 and +1 are entered in chr parenthesis. If I remove -1 or +1 the text is not encrypted. Could someone explain why this is the case. Any help would be much appreciated.

Regards
sauce1979

Private Sub cmdDecrypt_Click()
Dim sDecryptedCharacter As String
Dim sDecryptedMessage As String
Dim iCounter As Integer
' Check if user enters text
If txtAreaWrite <> "" Then
' Iterate through each character in the message.
For iCounter = 1 To Len(txtAreaWrite.Value)
sDecryptedCharacter = Asc(Mid(txtAreaWrite.Value, iCounter, 1))
' Convert the character code (shifted by -1) back
' to a character.
sDecryptedCharacter = Chr(sDecryptedCharacter - 1)
' Add the decrypted character to the new decrypted message.
sDecryptedMessage = sDecryptedMessage + sDecryptedCharacter
Next iCounter
' Display the decrypted message.
txtAreaWrite.Value = sDecryptedMessage
End If
End Sub


Private Sub cmdEncrypt_Click()
Dim sEncryptedCharacter As String
Dim sEncryptedMessage As String
Dim iCounter As Integer
If txtAreaWrite.Value <> "" Then
' Iterate through each character in the message.
For iCounter = 1 To Len(txtAreaWrite.Value)
' Convert one character at a time to its equivalent
' character code.
sEncryptedCharacter = Asc(Mid(txtAreaWrite.Value, iCounter, 1))
' Convert the character code (shifted by 1) back
' to a character.
sEncryptedCharacter = Chr(sEncryptedCharacter + 1)
' Add the encrypted character to the new encrypted message.
sEncryptedMessage = sEncryptedMessage + sEncryptedCharacter
Next iCounter
' Display the encrypted message.
txtAreaWrite.Value = sEncryptedMessage
End If
End Sub
 
You should take a look at an ASCII chart.

When you add 1 to the ASCII value of a "character", you are actually saying to use the next letter. So if I encrypt the letter "B" with this algorithm, I would expect to see the letter "A".

I prefer to use an encryption routine similar to this that multiplies the ASCII of the character times 2. It makes it a little harder to "read" the encrypted characters (because not all the characters are visible).

The use of the word "shifted" in the comments is mis-leading. Multiplying by 2 is actually "shifting" (i.e. moving the bits to the right). All this algorithm does is uses an adjacent letter in the alphbet...not very encrypted at all.
 
Thanks!! Much clearer now.
 

Users who are viewing this thread

Back
Top Bottom