首页 > Excel专区 > Excel函数 >

EXCEL如何使用VBA一次罗列表中三省的员工姓名?

Excel函数 2023-01-13

请罗列“四川省”、“湖南省”、“湖北省”三个省份员工的资料。

VBA代码如下:

Sub test()
‘定义变量
Dim rng As Range, RngTemp As Range, firstAddress As String
Dim i As Byte, findCell As Range, sh As Worksheet, shtname As String
‘将查找的目标设置为C2单元格到C列最后一个非空单元格赋予变量为rng
Set rng = Range([C2], Cells(Rows.Count, "C").End(xlUp))
‘循环赋予查找数组的每一个元素
For i = 0 To UBound(Array("四川省", "湖南省", "湖北省"))
‘开始查找数据,按值精确查找,不区分大小写
Set RngTemp = rng.Find(What:=Array("四川省", "湖南省", "湖北省")(i), LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False)
‘ 如果找到目标,则赋予该目标的单元格地址给firstAddress
If Not RngTemp Is Nothing Then
firstAddress = RngTemp.Address
Do
‘变量findCell没有初始化,则需要初始化,否则合并查找到的数值
If findCell Is Nothing Then
Set findCell = RngTemp
Else
Set findCell = Union(findCell, RngTemp)
End If
‘查找下一个
Set RngTemp = rng.FindNext(RngTemp)
‘循环到不为第一个找到的目标地址为止
Loop While RngTemp.Address <> firstAddress
End If
Next i
‘如果查找的内容不为空,则选择查找到内容所在行,否则显示提醒
If Not findCell Is Nothing Then
findCell.EntireRow.Select
Else
MsgBox "没有找到符合条件的数据!"
Exit Sub
End If
‘防止错误
On Error Resume Next
‘把当前工作表的名称赋予shtname
shtname = ActiveSheet.Name
Set sht = Sheets("查询结果")
‘如果不存在查询结果表,则添加一个“查询结果”工作表
If Err.Number <> 0 Then
Sheets.Add after:=Sheets(Sheets.Count)
Sheets(Sheets.Count).Name = "查询结果"
Else
Sheets(Sheets.Count).Cells.Clear
End If
Sheets(shtname).Select
Selection.Copy Sheets(Sheets.Count).[A1]
End Sub


Copyright © 2016-2023 office学习教程网 office.tqzw.net.cn. All Rights Reserved.