我是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