公式(1):=IF(LEFT(A1,2)="北京","北京","上海")
公式(2):=IF(FIND("北京",A1),","北京","上海")
两个公式都可以完成任务
sub test()
r = Range("A65536").End(xlUp).Row '最后一行
Cells(2, 2).Select '选中b2
Selection.FormulaR1C1 = "=Mid("RC[-1]",1,2)"
'取前单元格的前两字
Selection.AutoFill Destination:=Range(Cells(2, 2), Cells(r, 2)),Type:=xlFillDefault'将b列填充公式
end sub
mid("",1,2) 缺陷是 返回两个字的地名 如果是三个字 mid("",1,3)
在B2中输入下列公式:
=IF(NOT(ISERROR(SEARCH("上海",A3))),"上海",IF(NOT(ISERROR(SEARCH("北京",A3))),"北京",""))
Sub Macro1() '此过程对所有行计算
Dim i As Integer
Dim str As String
For i = 1 To 3
str = Cells(i, 1) '第i行第一列,即A列
If InStr(str, "北京") Then
Cells(i, 2) = "北京"
ElseIf InStr(str, "上海") Then
Cells(i, 2) = "上海"
End If
Next i
End Sub
Sub Macro2() '选中第2列某个表格再调用此宏,可为宏设置个快捷键
Dim i As Integer
Dim str As String
i = Selection.Row'选中的表格行数
str = Cells(i, 1) '第i行第一列
If InStr(str, "北京") Then
Cells(i, 2) = "北京"
ElseIf InStr(str, "上海") Then
Cells(i, 2) = "上海"
End If
End Sub
假设那三个数据分别放在1,2,3行,为你写了两个VBA宏,选一个适合你的。
=VLOOKUP(A2,A:A,1)