如何使用替换函数来解密和加密消息

时间:2017-12-06 11:14:28

标签: excel excel-vba vba

我希望通过将字符A更改为N来加密和解密消息,并将B更改为O ..就像您在我的代码中看到的那样。我需要一些帮助,谢谢!!

Sub MacroCryptage()
Dim ws1 As Worksheet
Set ws1 = Worksheets("Feuil1")
Dim rng As Range, cell As Range
Set rng = ws1.Range("G" & 6)
Set cell = ws1.Range("G" & 5)

    rng = WorksheetFunction.Substitute(cell, "A", "N")
    rng = WorksheetFunction.Substitute(cell, "B", "O")
    rng = WorksheetFunction.Substitute(cell, "C", "P")
    rng = WorksheetFunction.Substitute(cell, "D", "Q")
    rng = WorksheetFunction.Substitute(cell, "E", "R")
    rng = WorksheetFunction.Substitute(cell, "F", "S")
    rng = WorksheetFunction.Substitute(cell, "G", "T")
    rng = WorksheetFunction.Substitute(cell, "H", "U")
    rng = WorksheetFunction.Substitute(cell, "I", "V")
    rng = WorksheetFunction.Substitute(cell, "J", "W")
    rng = WorksheetFunction.Substitute(cell, "K", "X")
    rng = WorksheetFunction.Substitute(cell, "L", "Y")
    rng = WorksheetFunction.Substitute(cell, "M", "Z")
    rng = WorksheetFunction.Substitute(cell, "N", "A")
    rng = WorksheetFunction.Substitute(cell, "O", "B")
    rng = WorksheetFunction.Substitute(cell, "P", "C")
    rng = WorksheetFunction.Substitute(cell, "Q", "D")
    rng = WorksheetFunction.Substitute(cell, "R", "E")
    rng = WorksheetFunction.Substitute(cell, "S", "F")
    rng = WorksheetFunction.Substitute(cell, "T", "G")
    rng = WorksheetFunction.Substitute(cell, "U", "H")
    rng = WorksheetFunction.Substitute(cell, "V", "I")
    rng = WorksheetFunction.Substitute(cell, "W", "J")
    rng = WorksheetFunction.Substitute(cell, "X", "K")
    rng = WorksheetFunction.Substitute(cell, "Y", "L")
    rng = WorksheetFunction.Substitute(cell, "Z", "M")

End Sub

1 个答案:

答案 0 :(得分:0)

您当前的问题是您的解决方案仅适用于两个指定的单元格。您应该将其编写为接受原始文本并返回编码字符串

的函数

你在看什么是ROT13。实现此目的的最简单方法是使用字符的ASCII值。在VBA中,您可以使用ASC()函数返回char的ascii值,然后添加13,然后使用CHR()函数将该值转换回字符。此版本仅适用于大写文本 - 字符65到90.小写运行97到122,因此如果您需要,可以为此添加测试

Public Function Cypher(origtext as string) as string
dim s as string
dim answer as string
dim x as integer
dim myvar as integer
for x = 1 to len(origtext)
     s = mid(origtext,x,1)
     myvar = asc(s)+13
     if myvar > 90 then myvar = 65 + (myvar-90)
     s = chr(myvar)
     answer = answer & s
next x
Cypher = answer
End Function

要使用此功能,请在电子表格中输入= Cypher(单元格引用),其中单元格ref包含您要加密的文本