在循环中运行string分割函数

我有一个Excel表格,列中填充了大约10个完整的标准地址,间歇性空白(空白)

所有的地址都是相同的格式:

123街道名称,郊区QLD 4123

我想要做的是创build一个自动拆分器,其中BUtton7_Clickmacros通过列循环,并将数字,郊区,州代码和邮政编码拆分成单独的列的街道名称。 由于贡献者在这里,我得到了一个很好的核心function工作,分离地址作为一个静态值。

Sub Button7_Click() Dim strTest As String Dim arr1 Dim arr2 Dim StreetAddress As String Dim Postcode As String Dim StateCode As String Dim SubUrb As String strTest = "62 Norma Rd, Myaree WA 6154" arr1 = Split(strTest, ",") arr2 = Split(Trim(arr1(1)), Space(1)) StreetAddress = arr1(0) Postcode = arr2(2) StateCode = arr2(1) SubUrb = arr2(0) Range("E3").Value = arr1(0) Range("F3").Value = arr2(0) Range("G3").Value = arr2(1) Range("H3").Value = arr2(2) End Sub 

我正面临的问题是让这个运行…

  1. 在一个循环中
  2. 独立的列大小(但是我知道我需要使用像“For LngRow = 2 To Wksht.Range(”D“&Wksht.Rows.Count).End(xlUp).Row”
  3. 忽略空值(如果需要使用Len(address_string)> 0则退出)
  4. 使用ubound作为双名郊区。

我认为最好的第一步是构build循环,然后实施案例validation,然后列数和最后ubound。

然而,我尝试使用循环function在我的最后一个问题,但它没有工作,我从来没有使用ubound之前,有人可以帮助我吗?

 Sub Button7_Click() Dim strTest As String Dim arr1 Dim arr2 Dim StreetAddress As String Dim Postcode As String Dim StateCode As String Dim Suburb As String Dim LngRow As Long Dim i As Integer With ActiveSheet For LngRow = 2 To .Range("D" & .Rows.Count).End(xlUp).Row strTest = .Cells(LngRow, 4).Value If Len(Trim(strTest)) > 0 Then arr1 = Split(strTest, ",") If UBound(arr1) - LBound(arr1) < 1 Then MsgBox "No comma in address on row " & LngRow & " '" & strTest & "'" Else arr2 = Split(Trim(arr1(1)), Space(1)) If UBound(arr2) - LBound(arr2) < 2 Then MsgBox "Only " & UBound(arr2) - LBound(arr2) & " spaces after the comma in address on row " & LngRow & " '" & strTest & "'" Else StreetAddress = arr1(0) Postcode = arr2(UBound(arr2)) StateCode = arr2(UBound(arr2) - 1) Suburb = "" For i = LBound(arr2) To UBound(arr2) - 2 Suburb = Suburb & " " & arr2(i) Next .Cells(LngRow, 5).Value = Trim(StreetAddress) .Cells(LngRow, 6).Value = Trim(Suburb) .Cells(LngRow, 7).Value = Trim(StateCode) .Cells(LngRow, 8).Value = Trim(Postcode) End If End If End If Next End With End Sub 

或者,可以使用Range.TextToColumns方法将包含文本的单元格列parsing为多个列。 在这里,我假设你的地址数据在A列和郊区只有一个字:

 Sub AddressSpliter() Dim LastRow&, iRow& On Error Resume Next Application.DisplayAlerts = False LastRow = Cells(Rows.Count, 1).End(xlUp).Row For iRow = 2 To LastRow Cells(iRow, 1).TextToColumns Destination:=Cells(iRow, 2), DataType:=xlDelimited, Comma:=True ResetText2Columns Cells(iRow, 3).TextToColumns Destination:=Cells(iRow, 3), DataType:=xlDelimited, Space:=True ResetText2Columns Next Application.DisplayAlerts = True End Sub Sub ResetText2Columns() On Error Resume Next Cells(2, 1).TextToColumns Destination:=Cells(2, 1), DataType:=xlDelimited, ConsecutiveDelimiter:=False, _ Tab:=False, Semicolon:=False, Comma:=False, Space:=False, Other:=False, OtherChar:=False End Sub