我大约有15个地址,其格式如1111 Really Cool Street, Sweet City, Awesome State
,我需要将其分为街道,城市和州的单独单元格。
我当前遇到的问题是存储街道,城市和州。我已经尝试了一些方法。
Dim addressArray() As String
posRow = 1
Do
posRow = posRow + 1
addressFromCell= Sheet1.Cells(posRow , "C")
addressArray() = Split(addressFromCell, ",")
Sheet2.Cells(posRow , "A") = addressArray(0)
Sheet2.Cells(posRow , "B") = addressArray(1)
Sheet2.Cells(posRow , "C") = addressArray(2)
Loop Until posRow = 15
我认为addressArray
看起来像{"1111 Really Cool Street","Sweet City", "Awesome State"}
,我可以简单地传入我想要的元素。相反,我继续得到
运行时错误'9':下标超出范围
任何帮助都会很棒,谢谢!
答案 0 :(得分:2)
正如肯·怀特(Ken White)所指出的,导致该错误的原因是其中一个值不包含2个逗号。
这是我要怎么做:
Dim addressArray() As String
posRow = 1
Do
posRow = posRow + 1
addressArray() = Split(Sheet1.Cells(posRow, "C").Value, ",")
Sheet2.Cells(posRow, "A").Resize(1, UBound(addressArray) + 1).Value = addressArray()
Loop Until posRow = 15
此代码使用UBound
function检索数组的上限(最后一个元素的编号),并确保Range的大小始终与Array相同。
答案 1 :(得分:0)
为避免发生此类错误,您应该检查单元格是否为空,并且该单元格中的地址不是完整地址。
posRow = 1
Do
posRow = posRow + 1
addressFromCell = Sheet1.Cells(posRow, "C")
If addressFromCell <> "" Then
addressArray() = Split(addressFromCell, ",")
If UBound(addressArray) = 2 Then
Sheet2.Cells(posRow, "A") = addressArray(0)
Sheet2.Cells(posRow, "B") = addressArray(1)
Sheet2.Cells(posRow, "C") = addressArray(2)
End If
End If
Loop Until posRow = 15
答案 2 :(得分:0)
尝试
Sub test()
Dim vArray
Dim vDB, vR()
Dim i As Long, r As Long, j As Integer
Dim k As Integer
Dim s, e
's = Timer
vDB = Range("c2", "c15")
r = UBound(vDB, 1)
ReDim vR(1 To r, 1 To 3)
For i = 1 To r
vArray = Split(vDB(i, 1), ",")
k = UBound(vArray)
If k > 0 And k < 3 Then
For j = 1 To k
vR(i, j) = vArray(j - 1)
Next j
End If
Next i
With Sheet2
.Range("a2").Resize(r, 3) = vR
End With
'e = Timer
'Debug.Print "Test() time : " & (e - s)
End Sub