我正在学习如何使用VBA。 我需要读取一个Integer并将其存储在一个Array中,将其分解为单个字符。 例如,如果我输入数字1927,我需要将其存储为
Array[0] = 1
Array[1] = 9
Array[2] = 2
Array[3] = 7
我一直在寻找如何做2天。有人可以帮忙吗?
答案 0 :(得分:3)
我发现转换为unicode字符串,然后在Chr(0)上进行拆分是创建单个字符数组的有效方法。
Dim str As String, arr As Variant, i as long
str = StrConv(CStr(1927), vbUnicode)
arr = Split(str, Chr(0))
redim preserve arr(ubound(arr)-1)
For i = LBound(arr) To UBound(arr)
Debug.Print arr(i)
Next i
Debug.Print Join(arr, vbNullString)
答案 1 :(得分:2)
这是一个可能的解决方案:
Option Explicit
Public Sub SplitIntToArray()
Dim inputString As String
inputString = "1927"
Dim cnt As Long
Dim myArr As Variant
ReDim myArr(Len(inputString) - 1)
For cnt = LBound(myArr) To UBound(myArr)
myArr(cnt) = Mid(inputString, cnt + 1, 1)
Next cnt
For cnt = LBound(myArr) To UBound(myArr)
Debug.Print myArr(cnt)
Next cnt
End Sub
它需要inputString
,并根据其长度标注myArr
。然后它循环新的尺寸化数组,并将Mid(inputString, cnt+1,1)
分配给数组的每个部分。需要cnt+1
,因为字符串的第一个字符必须位于数组的第0个元素中,因为数组从零开始。
你也可以创建一个函数,取string
并返回数组:
Public Sub SplitIntToArray()
Dim inputString As String
Dim cnt As Long
Dim myArr As Variant
myArr = stringToArray("1927")
For cnt = LBound(myArr) To UBound(myArr)
Debug.Print myArr(cnt)
Next cnt
End Sub
Public Function stringToArray(inputString As String) As Variant
Dim cnt As Long
Dim returnArray As Variant
If Len(inputString) = 0 Then
stringToArray = Array()
Exit Function
End If
ReDim returnArray(Len(inputString) - 1)
For cnt = LBound(returnArray) To UBound(returnArray)
returnArray(cnt) = Mid(inputString, cnt + 1, 1)
Next cnt
stringToArray = returnArray
End Function
答案 2 :(得分:2)
答案 3 :(得分:2)
这是另一种解决方案,它不需要循环来将值分配给数组,或者从数组分配给字符串。
Sub Ex()
Dim Integers() As Byte
Dim i As Long
Integers = StrConv("0123456789", vbFromUnicode)
'Print the values out, already in an array
For i = LBound(Integers) To UBound(Integers)
Debug.Print Chr$(Integers(i))
Next
'Put back into a string
Dim MyInts As String
MyInts = StrConv(Integers, vbUnicode)
Debug.Print MyInts
End Sub
答案 4 :(得分:1)
似乎没有人使用过数学路线。所以,让我这样做。
Sub numArr()
Dim num As Integer
Dim arr() As Integer
num = 1927
i = 0
Do
i = i + 1
ReDim Preserve arr(i)
arr(i) = num Mod 10
num = num \ 10
Loop While num > 0
End Sub
这个写作更有趣。