在相同的字符串输入上使用InStr查找下一个事件

时间:2019-04-12 20:03:38

标签: excel vba string

我目前正在读取一个用逗号分隔的csv文件中的地址数据。数据如下:

123 Main St, Rubber Boots, MANITOBA

数据的顺序始终是街道地址,城市,省份。

我正在尝试使用InStr来查找逗号的位置,我可以轻松地对第一个进行此操作,但是使用它来查找第二次出现是一个问题。我正在尝试获取每个子字符串并将其修剪以输出到excel中自己的单元格中。修剪中间子字符串时,我仍然剩下其余的字符串,是否有办法解决,以便“ MANITOBA”将位于其自己的单元格中?谢谢!

city = ""
province = ""
streetAddress = ""
shippingAddress = CStr(Sheet1.Cells(currRawRow, "C"))
commaPos = InStr(1, shippingAddress, ",")
If (commaPos > 0) Then
     streetAddress = Trim(Left(shippingAddress, (commaPos - 1)))
     commaPos = InStr(commaPos, shippingAddress, ",")
     city = Trim(Mid(shippingAddress, (commaPos + 1)))
End If

当前输出: enter image description here

使用拆分更新代码:

city = ""
province = ""
streetAddress = ""
shippingAddress = CStr(Sheet1.Cells(currRawRow, "C"))
shippingParts = Split(shippingAddress, ",")
streetAddress = shippingParts(0)
city = shippingParts(1)
province = shippingParts(2)

更新后的输出:

enter image description here

2 个答案:

答案 0 :(得分:4)

尽可能使用Split代替Instr

Sub tester()
    Dim s As String
    Dim a() As String

    s = "123 Main St, Rubber Boots, MANITOBA"

    a = Split(s, ",")

    Debug.Print a(0)
    Debug.Print a(1)
    Debug.Print a(2)
End Sub

答案 1 :(得分:1)

Sub manitoba()
Const addressString = "123 Main St, Rubber Boots, MANITOBA"
Dim str1 As String
Dim str2 As String
Dim str3 As String
Dim tempString As String
tempString = addressString

str1 = Mid(tempString, 1, InStr(tempString, ",") - 1)
tempString = Mid(tempString, InStr(tempString, ",") + 1, Len(tempString))
Debug.Print str1

str2 = Mid(tempString, 1, InStr(tempString, ",") - 1)
Debug.Print str2

str3 = Mid(tempString, InStr(tempString, ",") + 1, Len(tempString))
Debug.Print str3
End Sub

我确信有人甚至可以制定出更优雅的递归函数。我现在太累了:P