我是VBA的新手,并且在我尝试编写的宏中使用If语句时遇到了一些困难。每个月我都会在Excel中收到一份报告,列出我们公司的哪些员工执行了某些任务。我正在撰写的宏旨在将每位员工的数据复制并粘贴到主工作簿中。嵌套If语句遇到问题
我遇到的问题是定义我需要复制的范围。正如您在代码中看到的那样,员工在列B中列出。我首先在列B中搜索员工。如果他们不存在,宏将在主工作簿中的名称下复制并粘贴(无) 。如果它找到了它们的名字,它将它们名字下面的行设置为第一个变量。
这里是我遇到问题的地方。下一步是找到列出的下一名员工,并将上面的行设置为第二个变量。然后我使用第一个和第二个变量来复制和粘贴该行的范围。我使用If语句循环查找列出的下一位员工。但是,我的嵌套If语句在我的第二个Else if语句后结束。有没有人知道我可以更好地写这个的方法?我尝试使用Select Case语句,但无法获得正确的语法。
Sub EmployeeActivity()
Dim Employee1 As Integer, Employee2 As Integer, Employee3 As Integer, Employee4 As Integer
Dim EmployeeRange As Range, rngSelectFind As Range, rngPasteFind As Range
Windows("Activities Report.xlsm").Activate
Set rngSelectFind = Columns("B:B").Find(What:="Employee 1", After:=Range("B1"), LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext)
If Not rngSelectFind Is Nothing Then
Employee1 = rngSelectFind.Row + 1
ElseIf rngSelectFind Is Nothing Then
Set rngSelectFind = Columns("B:B").Find(What:="(none)", After:=Range("B1"), LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext)
Consultant3 = rngSelectFind.Row
End If
Set rngSelectFind = Columns("B:B").Find(What:="Employee 2", After:=Range("B1"), LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext)
If Not rngSelectFind Is Nothing Then
Employee2 = rngSelectFind.Row - 1
ElseIf rngSelectFind Is Nothing Then
Set rngSelectFind = Columns("B:B").Find(What:="Employee 3", After:=Range("B1"), LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext)
If Not rngSelectFind Is Nothing Then
Employee2 = rngSelectFind.Row - 1
End If
ElseIf rngSelectFind Is Nothing Then
Set rngSelectFind = Columns("B:B").Find(What:="(none)", After:=Range("B1"), LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext)
If Not rngSelectFind Is Nothing Then
Employee2 = rngSelectFind.Row - 1
End If
End If
If Employee1 > 0 And Employee2 > 0 Then
Set EmployeeRange = Range(Cells(Employee1, 2), Cells(Employee2, 7))
ElseIf Employee3 > 0 Then
Set EmployeeRange = Range(Cells(Employee3, 2), Cells(Employee3, 7))
End If
EmployeeRange.Select
Selection.Copy
Windows("Monthly Activity Report.xlsm").Activate
Sheets("April '13").Activate
Set rngPasteFind = Columns("A:A").Find(What:="Employee Activities", After:=Range("A1"), LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext)
If Not rngPasteFind Is Nothing Then
Employee4 = rngPasteFind.Row + 1
End If
Range(Cells(Employee4, 1), Cells(Employee4, 6)).Select
Selection.Insert (xlShiftDown)
End Sub
非常感谢您的帮助。请让我知道,如果我可以提供额外的背景。
可能会有所帮助,如果你能提供的文件(S),如果有必要的匿名数据(假设它是与工作相关的/可能保密的/ etc。) – 2013-05-06 20:53:57