我正在尝试创建一个更改字符串中的字母的程序,并且我继续遇到明显的问题,如果它更改了一个值,说它将A更改为M,当它到达M时它会将M更改为其他东西,所以当我运行代码将其全部改回来时,它会转换它,好像这封信最初是M而不是A。
任何想法如何使代码不会改变它已经改变的字母?
至于代码我刚刚得到了大约40行(我确定这是一个更干净的方式,但我是新的vba,当我尝试选择案例它只会改变一个字母,而不是通过所有这些)< / p>
Text1.value = Replace(Text1.value, "M", "E")
答案 0 :(得分:4)
试试这个:
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
答案 1 :(得分:1)
使用MID功能循环播放它。类似的东西:
MyVal = text1.value
For X = 1 to Len(MyVal)
MyVal = Replace(Mid(MyVal, X, 1), "M", "E")
X = X + 1
Next X
编辑:好的,进一步的光,我会做出一个改变。将对存储在表中。然后你可以使用DLookup进行翻译,使用相同的概念:
MyVal = text1.value
For X = 1 to Len(MyVal)
NewVal = DLookup("tblConvert", "fldNewVal", "fldOldVal = '" & Mid(MyVal, X, 1) & "")
MyVal = Replace(Mid(MyVal, X, 1), Mid(MyVal, X, 1), NewVal)
X = X + 1
Next X
答案 2 :(得分:0)
这是使用less循环的另一种方法
Public Function Obfuscate(sInput As String) As String
Dim vaBefore As Variant
Dim vaAfter As Variant
Dim i As Long
Dim sReturn As String
sReturn = sInput
vaBefore = Split("a,m,s,r,t", ",")
vaAfter = Split("m,z,r,q,a", ",")
For i = LBound(vaBefore) To UBound(vaBefore)
sReturn = Replace$(sReturn, vaBefore(i), "&" & Asc(vaAfter(i)))
Next i
For i = LBound(vaAfter) To UBound(vaAfter)
sReturn = Replace$(sReturn, "&" & Asc(vaAfter(i)), vaAfter(i))
Next i
Obfuscate = sReturn
End Function
它将每个字母变成&符号+替换字母ascii代码。然后它会替换替换字母中的每个ascii代码。
嵌套循环花了大约5毫秒对20毫秒。