将数字字符转换为字母字符
我试图得到I / O如下:
input:123490
输出:BCDEJA
逻辑很简单:
如果
strarr(i)=0,1,2,3,4,5,6,7,8,9
然后
strarr(i) should be = A,B,C,D,E,F,G,H,I,J
码
str = .Cells(18, "B").Value strarr() = Split(str) For i = LBound(strarr) To UBound(strarr) If strarr(i) = 0 Then .Cells(24, "B") = "A" & .Cells(24, "B") Else If strarr(i) = 1 Then .Cells(24, "C") = "B" & .Cells(24, "C") Else If strarr(i) = 2 Then .Cells(24, "C") = "C" & .Cells(24, "C") Else If strarr(i) = 3 Then .Cells(24, "D") = "D" & .Cells(24, "D") Else . . . If strarr(i) = 9 Then .Cells(24, "J") = "J" & .Cells(24, "J") Else End If x10 times Next i .Cells(24, "B") = .Cells(24, "B") & .Cells(24, "C") & .Cells(24, "D") & .Cells(24, "E") & .Cells(24, "F") & .Cells(24, "G") & .Cells(24, "H") & .Cells(24, "I") & .Cells(24, "I") & .Cells(24, "J") .Cells(18, "D").Value = .Cells(24, "B") Worksheets("Functions").Rows(24).ClearContents End With
任何人都可以帮我解决我错了吗?
使用ASCII字符编号(…?)并根据您要转换的数字进行调整。 国会大厦A是ASCII 0×41或65十二月。
Function num_alpha(str As String) Dim sTMP As String, d As Long For d = 1 To Len(str) sTMP = sTMP & Chr(65 + Mid(str, d, 1)) Next d num_alpha = sTMP End Function
像任何本地工作表函数一样使用。 在D18中,
=num_alpha(B18)
我喜欢Jeeped的回答。
下面的版本在这方面做了一些调整,以发挥速度:
- 作为一名LHS操作员(因为VBA中的连接速度较慢)
- 使用
Mid$
和ChrW$
在我的testing中,运行时间缩短了40%(见下面的编辑)
Function NumChr(strIn As String) As String Dim strTemp As String Dim lngChar As Long For lngChar = 1 To Len(strIn) Mid$(strIn, lngChar, 1) = ChrW$(65 + Mid$(strIn, lngChar, 1)) Next NumChr = strTemp End Function
编辑:添加testing
- 初始代码为3.21秒
- 秒代码为1.98秒
高层次的和解
- 在第一代码中使用
Mid$
而不是Mid
代码从3.21秒到2.77秒。 - 使用
ChrW$
而不是Chr
从2.77秒到2.43秒。 - 在LHS上使用Mid $需要1.98秒
先前的代码
Function num_alpha(str As String) Dim sTMP As String, d As Long For d = 1 To Len(str) sTMP = sTMP & Chr(65 + Mid(str, d, 1)) Next d num_alpha = sTMP End Function
新的代码
Function NumChr(strIn As String) As String Dim lngChar As Long For lngChar = 1 To Len(strIn) Mid$(strIn, lngChar, 1) = ChrW$(65 + Mid$(strIn, lngChar, 1)) Next NumChr = strIn End Function
testing时机
Sub Main() Call Test Call Test2 End Sub Sub Test() Dim dbTimer As Double dbTimer = Timer() For i = 1 To 1000000 s = num_alpha("123490") Next Debug.Print Timer() - dbTimer End Sub Sub Test2() Dim dbTimer As Double dbTimer = Timer() For i = 1 To 1000000 s = NumChr("123490") Next Debug.Print Timer() - dbTimer End Sub
由于Jeeped说你可以使用Chr
函数将一个数字转换成一个字母,使用ASCII。
在另一个说明,当使用一个单一的variables,可以有多个值,而不是使用这么多, if
我build议使用case select
模型,使用strarr(i)
作为控制器,它会简化你的代码,将是一个更多的可读性。
此外,而不是写入单元格的不同值,我会使用一个临时variables来存储汇总的价值,减less麻烦为你和快一点,因为你不读/写入表,而只是在的背景
=CHAR(64 + 1) will Give "A" =CHAR(64 + 2) will Give "B" =CHAR(64 + 3) will Give "C" so on.....
这应该让你开始:
Public Function ConvertValue(iInput As Integer) As String ConvertValue = Chr(65 + iInput) End Function
请注意,大写字母“A”的值为“65”,小写字母从'97开始