我正在编写一个宏,它将获取一个大型数据表并将其过滤到另一个工作表上,第一个标准基于由基于m的下一个循环的迭代确定的变量(Degree Level),以及基于变量(Major)的第二标准,由基于i的嵌套下一循环的迭代确定。
过滤器在m的第一次迭代中工作,但在第二次迭代时不起作用(只有三次迭代)。不确定会导致错误的是什么,但它位于“填充过滤数据表...”下面的行上面。下面是我的代码。提前谢谢!
Public SelColCode as string
Sub FilterGrads()
Dim DegreeLevel as string
SelColCode = "H"
For m = 1 To 3
If m = 1 Then
DegreeLevel = "B"
Number_Of_Majors = Sheets("MajorList").Range("AC1").Value '16 in this case
ElseIf m = 2 Then
DegreeLevel = "M"
Number_Of_Majors = Sheets("MajorList").Range("AE1").Value '12 in this case
ElseIf m = 3 Then
DegreeLevel = "D"
Number_Of_Majors = Sheets("MajorList").Range("AE1").Value '8 in this case
End If
'Look through all the majors and fill in each row one at a time on the report
For i = 5 To 4 + Number_Of_Majors * 2 Step 2
'Select the Report Tab and select the major
Sheets(SelColCode & " " & DegreeLevel & " Report").Select
Major = Range("B" & i)
'Unhide the advance filter tab and then input the Degree level and major from above
ThisWorkbook.Worksheets("Advance Filter").Visible = True
ThisWorkbook.Worksheets("Advance Filter").Select
Range("A6:AA15").ClearContents
Range("E6").Value = DegreeLevel & ".*"
Range("F6").Value = Major
'Check if the "Filter Data" Tab exists and delete it then add a blank sheet with the same name.
Application.DisplayAlerts = False
On Error Resume Next
ThisWorkbook.Sheets("Filter Data").Delete
On Error GoTo 0
Application.DisplayAlerts = True
Sheets.Add.Name = "Filter Data"
Sheets("Filter Data").Select
Sheets("Filter Data").Move After:=Sheets("Merged Data")
'Populate filtered data sheet using the advance filter function
Sheets("Merged Data").Range(Data_Range).AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=Sheets("Advance Filter").Range("A5:AB6"), CopyToRange:=Range("A1"), Unique:=True
'Length of filtered data minus one to not include the variable titles is the number of graduates for that major
Grads = ActiveSheet.Cells(Rows.count, "A").End(xlUp).Row - 1
'do some stuff, then loop
Next 'i, major
Next 'm, degreelevel
End Sub
答案 0 :(得分:0)
所以我不确定为什么会这样,但我为每个学位级别制作了一个过滤数据选项卡,然后为每个学位级别选项创建了一个单独的If语句。以下是每个If级别。感谢您试用@everyonewhohelped
'Check if the "Filter Data" Tab exists and delete it then add a blank sheet with the same name.
Application.DisplayAlerts = False
On Error Resume Next
ThisWorkbook.Sheets("Filter Data B").Delete
On Error GoTo 0
Application.DisplayAlerts = True
Sheets.Add.Name = "Filter Data B"
Sheets("Filter Data B").Range("A1").Select
'Populate filtered data sheet using the advance filter function
Sheets("Merged Data").Range("A1").CurrentRegion.AdvancedFilter _
Action:=xlFilterCopy, _
CriteriaRange:=Sheets("Advance Filter").Range("A5:AB7"), _
CopyToRange:=Range("A1"), _
Unique:=False
'Length of filtered data minus one to not include the variable titles is the number of graduates for that major
Grads = ActiveSheet.Cells(Rows.count, "A").End(xlUp).Row - 1