晚上有个朋友打电话问我可不可以给他做个小程序,要实现的功能比较简单,想把"xxx省xxx市xxx区(县)"这类的字符串拆分成省市区三段,由于原本数据就是在excel中存放的,想了想应该可以通过VBA来实现,虽然没搞过,但想想应该不难(google+baidu+msdn 无敌),就答应了。
功能是现实了,但感觉写的比较烂,应该还可以优化,不过可以先交差了,哈哈
Sub split_placeName()
Dim sTotalName As String '代表全名
Dim sProvince As String '表示省名称
Dim sCity As String '表示城市名称
Dim sArea As String '表示县或者区名称
Dim posP, posC, posA
Dim i As Integer
For i = Selection.Row To (Selection.Row + Selection.Rows.Count - 1)
posP = 0
posC = 0
posA = 0
'清空单元格
Cells(i, 2) = ""
Cells(i, 3) = ""
Cells(i, 4) = ""
'保存全名
sTotalName = Cells(i, 1)
If sTotalName <> "" Then
posP = InStr(sTotalName, "省") '查找是否有省
If posP > 0 Then
Cells(i, 2) = Mid(sTotalName, 1, posP)
End If
posC = InStr(sTotalName, "市") '查找是否有市
If posC > 0 Then
Cells(i, 3) = Mid(sTotalName, posP + 1, posC - posP)
Else
posC = posP '如果没有市,则将省作为县区的起始
End If
posA = InStr(sTotalName, "县")
If posA > 0 Then
Cells(i, 4) = Mid(sTotalName, posC + 1, posA - posC)
Else
posA = InStr(sTotalName, "区")
If posA > 0 Then
Cells(i, 4) = Mid(sTotalName, posC + 1, posA - posC)
End If
End If
End If
Next i
End Sub
Office2003 Excel宏的安全性可以通过HKEY_LOCAL_MACHINE/Software/Microsoft/Office/11.0/Excel/Security下的Level键值设置(2007的是12.0),Excel优先采用HKEY_LOCAL_MACHINE下面的设置,如果下面有Security Level设置,则应用它,而会忽略HKEY_CURRENT_USER下面的设置