|
本帖最后由 gbgbxgb 于 2016-8-2 21:54 编辑
谦虚好学,赞一个,下列代码供参考:
Set reg = CreateObject("VBScript.RegExp")
With reg
.Pattern = "^(([^省]+省)|(.+自治区))?([^市]+市)?([^区县]+(市|[^小]区|县))?(.+(街道办事处|街道办|街道|[^小]镇|乡))?(.+)?"
For i = 2 To UBound(arr)
theStr = arr(i, 1)
If theStr <> "" Then
Set theMatches = .Execute(theStr)
With theMatches(0)
For j = 0 To 8
theStr = .submatches(j)
Select Case j
Case 0
If theStr <> "" Then
brr(i - 1, 1) = theStr
Else
brr(i - 1, 1) = "山东省"
End If
Case 3
For k = 0 To UBound(a)
If theStr = a(k) Then
theProvinceYes = True
Exit For
End If
Next k
'
If Not theProvinceYes Then
brr(i - 1, 2) = theStr
Else
brr(i - 1, 1) = theStr
theProvinceYes = False
End If
Case 4
brr(i - 1, 3) = theStr
Case 6
brr(i - 1, 4) = theStr
Case 8
brr(i - 1, 5) = theStr
End Select
Next j
End With
End If
Next i
End With
事后补注:其中变体型变量a为 a = VBA.Array("北京市", "天津市", "上海市", "重庆市")
再注:
1.theProvinceYes是一逻辑变量,即定义Dim theProvinceYes as Boolean,该逻辑变量用于确定是否直辖市;
2.Select Case的结构效率不高,你若有兴趣,不嫌代码写的难看,那么改成If结构则其效率要高得多。
改了下,发现也不难看:
arr = .Range(.Cells(1, 1), .Cells(theFinalRow, 1))
ReDim brr(1 To UBound(arr) - 1, 1 To 5)
a = VBA.Array("北京市", "天津市", "上海市", "重庆市")
'
Set reg = CreateObject("VBScript.RegExp")
With reg
.Pattern = "^(([^省]+省)|(.+自治区))?([^市]+市)?([^区县]+(市|[^小]区|县))?(.+(街道办事处|街道办|街道|[^小]镇|乡))?(.+)?"
For i = 2 To UBound(arr)
theStr = arr(i, 1)
If theStr <> "" Then
Set theMatches = .Execute(theStr)
With theMatches(0)
For j = 0 To 8
theStr = .submatches(j)
If j = 0 Then
If theStr <> "" Then
brr(i - 1, 1) = theStr
Else
brr(i - 1, 1) = "山东省"
End If
ElseIf j = 3 Then
For k = 0 To UBound(a)
If theStr = a(k) Then
theProvinceYes = True
Exit For
End If
Next k
'
If Not theProvinceYes Then
brr(i - 1, 2) = theStr
Else
brr(i - 1, 1) = theStr
theProvinceYes = False
End If
ElseIf j = 4 Then brr(i - 1, 3) = theStr
ElseIf j = 6 Then brr(i - 1, 4) = theStr
ElseIf j = 8 Then brr(i - 1, 5) = theStr
End If
Next j
End With
End If
Next i
End With
.Cells(2, 3).Resize(UBound(brr), UBound(brr, 2)) = brr
|
评分
-
1
查看全部评分
-
|