使用 VBA 实现一个简单的替换密码 [英] Implementing a simple substitution cipher using VBA

查看:61
本文介绍了使用 VBA 实现一个简单的替换密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个程序来更改字符串中的字母,但我一直遇到一个明显的问题,即如果它更改了一个值,比如说它将 A 更改为 M,当它到达 M 时,它将将该 M 更改为别的东西,所以当我运行代码将其全部改回时,它会将其转换为好像字母最初是 M 而不是 A.

I am trying to make a program that changes letters in a string and i keep running into the obvious issue of if it changes a value, say it changes A to M, when it gets to M it will then change that M to something else, so when i run the code to change it all back it converts it as if the letter was originally an M not an A.

有什么想法可以让代码不改变已经改变的字母吗?

Any ideas how to make it so the code doesnt change letters its already changed?

至于代码,我只得到了大约 40 行(我确定有一种更简洁的方法来做到这一点,但我是 vba 新手,当我尝试选择大小写时,它只会更改一个字母,而不会遍历所有字母)

as for code ive just got about 40 lines of this (im sure theres a cleaner way to do it but im new to vba and when i tried select case it would only change one letter and not go through all of them)

Text1.value = Replace(Text1.value, "M", "E")

推荐答案

试试这个:

Dim strToChange As String
strToChange = "This is my string that will be changed"
Dim arrReplacements As Variant

arrReplacements = Array(Array("a", "m"), _
                        Array("m", "z"), _
                        Array("s", "r"), _
                        Array("r", "q"), _
                        Array("t", "a"))

Dim strOutput As String
strOutput = ""
Dim i As Integer
Dim strCurrentLetter As String

For i = 1 To Len(strToChange)
    strCurrentLetter = Mid(strToChange, i, 1)
    Dim arrReplacement As Variant

    For Each arrReplacement In arrReplacements
        If (strCurrentLetter = arrReplacement(0)) Then
            strCurrentLetter = Replace(strCurrentLetter, arrReplacement(0), arrReplacement(1))
            Exit For
        End If
    Next

    strOutput = strOutput & strCurrentLetter
Next

输出如下:

Thir ir zy raqing ahma will be chmnged

这篇关于使用 VBA 实现一个简单的替换密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆