我目前有一份已在整个公司内完成培训的员工名单。我正在尝试创建一个宏来通过他们的员工编号找到我部门的员工,然后将其复制到工作表2中。
员工编号位于A列。此员工的ID下可能有多个条目。我想将该行中的所有信息从A列复制到N列。我想将这些条目粘贴到Sheet2中。
我们部门内有187名员工。任何帮助完成这一点将不胜感激。
Sub ()
Worksheets("Sheet1").Activate
Range("A1").Activate
' Find the first ID Number
Cells.Find(What:="10503", After:=ActiveCell, SearchDirection:=xlPrevious).Select
' copy and paste Text2
ActiveCell.Offset(0, 0).Copy
Worksheets("Sheet2").Select
Range("A65000").End(xlUp).Offset(1, 0).Select
ActiveCell.PasteSpecial (xlPasteAll)
Worksheets("Sheet1").Activate
End Sub
答案 0 :(得分:1)
试试这个:
Sub FindandCopyRow()
Dim targetSh As Worksheet
Set targetSh = ThisWorkbook.Worksheets("Sheet2")
Dim i As Long
For i = 1 To Cells(Rows.Count, "A").End(xlUp).Row
If Cells(i, 1).Value = "10503" Then '--->change ID here as required
Rows(i).EntireRow.Copy Destination:=targetSh.Range("A" & targetSh.Cells(Rows.Count, "A").End(xlUp).Row + 1)
End If
Next i
End Sub
答案 1 :(得分:0)
我刚刚在@Mirig的答案中添加了一些数据。
一种是使用Application.InputBox
,提示用户插入员工编号,而不是每次都编辑代码的用户。
我也只是Sheet
引用了For
循环的各个部分,总是很好地引用你所在的工作表以避免为下一个用户和应用程序本身消费。
Sub FindandCopyRow()
Dim DataSh As Worksheet
Set DataSh = ThisWorkbook.Worksheets("Sheet1")
Dim targetSh As Worksheet
Set targetSh = ThisWorkbook.Worksheets("Sheet2")
Dim EmployeeNumber As Long
'This allows you to enter an employee number and not have to edit the code every time
EmployeeNumber = Application.InputBox(Prompt:="Please Enter Employee Number:", Type:=1)
'Try use descriptive naming for variables.....always
Dim DataShRowRef As Long
'Remember to always reference the sheet you are in when counting and copying etc
For DataShRowRef = 1 To DataSh.Cells(DataSh.Rows.Count, "A").End(xlUp).Row
If DataSh.Cells(DataShRowRef, 1).Value = EmployeeNumber Then
DataSh.Rows(DataShRowRef).EntireRow.Copy Destination:=targetSh.Range("A" & targetSh.Cells(targetSh.Rows.Count, "A").End(xlUp).Row + 1)
End If
Next DataShRowRef
End Sub