我正在尝试按如下方式获取I / O:
输入: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
任何人都可以帮我解决我错的地方吗?
答案 0 :(得分:10)
使用ASCII字符数字(......?)并按您要转换的数字进行调整。国会大厦 A 是ASCII 0×41或65 dec。
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)
答案 1 :(得分:4)
我喜欢Jeeped的回答。
下面的版本可以通过一些调整来实现速度:
Mid
作为LHS运算符(因为VBA中的串联较慢)Mid$
和ChrW$
我的测试减少了约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
编辑:添加测试
高级别对帐
Mid$
中使用Mid
从3.21到2.77秒使用代码。 ChrW$
而不是Chr
从2.77秒到2.43秒。先前代码
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
测试时间
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
答案 2 :(得分:3)
正如Jeeped所说,您可以使用Chr
函数将数字转换为字母,使用ASCII。
另一方面,当使用一个可以有多个值的变量时,我会建议使用if
模型而不是使用case select
这么多的strarr(i)
模型,使用{{1作为控制器,它可以简化你的代码并且更具可读性。
此外,我不会将不同的值写入单元格,而是使用临时变量来存储聚合值,减少对您的麻烦,并且在您不读取/写入工作表时更快一些#39;只是在后台工作
答案 3 :(得分:2)
这应该让你开始:
Public Function ConvertValue(iInput As Integer) As String
ConvertValue = Chr(65 + iInput)
End Function
请注意,' 65'的值代表大写字母A,小写字母代表' 97
答案 4 :(得分:2)
=CHAR(64 + 1)
will Give "A"
=CHAR(64 + 2)
will Give "B"
=CHAR(64 + 3)
will Give "C"
so on.....