Row\Col |
A |
B |
1 |
C:\Users\shg\Documents\App Data - Excel\Excel14 |
A1: Input |
2 |
H:\Yuhfo\aqw\Snxfzcxke\Sip Jxxc - Yflum\Dsnrj14 |
A2: =Vigenere(A1, "FGXECDOWUIJQBPZVLNYKRMHSTA", TRUE) |
3 |
C:\Users\shg\Documents\App Data - Excel\Excel14 |
A3: =Vigenere(A2, "FGXECDOWUIJQBPZVLNYKRMHSTA", FALSE) |
Function Vigenere(ByVal sMsg As String, _
ByVal sKey As String, _
Optional bEncrypt As Boolean = True) As String
' shg 2012, 2014
' Returns a string containing the Vigenere encryption or decryption of sMsg
' using key sKey. sKey must be a 26-character string containing the letters
' of the alphabet in scrambled order and nothing else.
' Characters in sMsg other than letters are preserved unchanged.
' Case is preserved.
Dim sOut As String
Dim iChr As Long ' character index
Dim iLtr As Long ' 0 to 25 for A to Z
sOut = sMsg
sMsg = UCase(sMsg)
sKey = UCase(Replace(sKey, " ", ""))
If sKey Like "*[!A-Z]*" Or Len(sKey) <> 26 Then
Vigenere = "Invalid key!"
Else
sKey = sRept(sKey, Len(sMsg) \ Len(sKey) + 1)
For iChr = 1 To Len(sMsg)
If Mid(sMsg, iChr, 1) Like "[A-Za-z]" Then
If bEncrypt Then
iLtr = (Asc(Mid(sMsg, iChr, 1)) + Asc(Mid(sKey, iChr, 1))) Mod 26
Else
iLtr = (Asc(Mid(sMsg, iChr, 1)) - Asc(Mid(sKey, iChr, 1)) + 26) Mod 26
End If
Mid(sOut, iChr) = Chr(iLtr + IIf(Asc(Mid(sOut, iChr)) <= 90, 65, 97))
End If
Next iChr
Vigenere = sOut
End If
End Function
Function sRept(sMsg As String, n As Long) As String
' Mimics WorksheetFunction.Rept
sRept = Replace(Space(n), " ", sMsg)
End Function
Bookmarks