给你写了一个自定义函数,用法跟普通函数一样,括号内为指定单元格。
代码如下,详见附件!
Public Function CTNcode(ByVal Rng As Range) As String
Dim s1 As String, s2 As String, s3 As String
Dim i As Long, arr()
i = Sheet2.[a65536].End(3).Row
arr = Sheet2.Range("A1:B" & i).Value
CTNcode = "-"
Dim dc As Object
Set dc = CreateObject("Scripting.Dictionary")
For i = 1 To UBound(arr)
If arr(i, 1) = "北京市" Or arr(i, 1) = "天津市" Or arr(i, 1) = "上海市" Or arr(i, 1) = "重庆市" Then
s1 = "": s2 = arr(i, 1): s3 = ""
ElseIf arr(i, 1) Like "*" & "省" Then
s1 = arr(i, 1): s2 = "": s3 = ""
ElseIf arr(i, 1) Like "*" & "市" Then
s2 = arr(i, 1): s3 = ""
Else
s3 = arr(i, 1)
End If
dc(s1 & s2 & s3) = arr(i, 2)
If Rng.Value Like s1 & s2 & s3 & "*" Then CTNcode = arr(i, 2)
Next
End Function
用到正则表达式 提取市区县之前的字符 与sheet2中的比较,获取行政区域代码