我正在为动态的,经过过滤的数据编写代码,我想通过标题引用列,而不是使用“ G”,“ H”等。我的代码应该查看列中的单元格F(cpass),然后查看5个相邻的单元格。如果这些相邻的单元格为空,则应删除整行,然后循环到F列中的下一个单元格。我的问题是,这些列是动态的(从报表中提取),并且在任何给定的列中都可能乱序天。我不知道如何在For语句中获取列引用。以下是我尝试编写的代码。任何建议将不胜感激!
Sub ClassPassDeleteNEWTEST()
Dim cpass As Integer, fmonth As Integer, init As Integer, lmonth As Integer, piftot As Integer, pifnotax As Integer, LR As Long, r As Long
cpass = Application.WorksheetFunction.Match("Class Pass", Range("A1:AZ1"), 0)
fmonth = Application.WorksheetFunction.Match("First Month Only-", Range("A1:AZ1"), 0)
init = Application.WorksheetFunction.Match("InitiationFee", Range("A1:AZ1"), 0)
lmonth = Application.WorksheetFunction.Match("Last Month Only-", Range("A1:AZ1"), 0)
piftot = Application.WorksheetFunction.Match("PIF Total", Range("A1:AZ1"), 0)
pifnotax = Application.WorksheetFunction.Match("PIF Total No Tax", Range("A1:AZ1"), 0)
LR = Cells(Rows.Count, cpass).End(xlUp).Row
For r = LR To 1 Step -1
If Range(fmonth & r).Value = "" And Range(init & r).Value = "" And _
Range(lmonth & r).Value = "" And Range(piftot & r).Value = "" And _
Range(pifnotax & r).Value = "" Then Rows(r).Delete
Next r
MsgBox ("All Class Passes with no payment have been deleted, and any with a payment have been cleared.")
ActiveSheet.Range("A:L").AutoFilter Field:=6
End Sub
答案 0 :(得分:3)
由于匹配返回列索引,因此请使用Cells
引用而不是Range
引用。您正在考虑标题范围A1:AZ1
,因此匹配的结果将是列索引。
将Range(fmonth & r)
更改为Cells(r, fmonth)
,依此类推。
答案 1 :(得分:0)
您应该关闭Application.ScreenUpdating
和Application.Calculation
以提高速度。
这是最简单的方法:
Sub ClassPassDeleteNEWTEST()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim cpass As Integer, r As Integer
cpass = Application.WorksheetFunction.Match("Class Pass", Rows(1), 0)
For r = Cells(Rows.Count, cpass).End(xlUp).Row To 1 Step -1
If WorksheetFunction.CountA(Rows(r).Columns("H:L")) = 0 Then Rows(r).Delete
Next r
ActiveSheet.Range("A:L").AutoFilter Field:=6
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
MsgBox ("All Class Passes with no payment have been deleted, and any with a payment have been cleared.")
End Sub
最好测试标题是否存在,并完全限定目标工作表的范围。
Sub ClassPassDeleteNEWTEST()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim cpass As Integer, r As Integer
With ThisWorkbook.Worksheets(1)
On Error Resume Next
cpass = Application.WorksheetFunction.Match("Class Pass", .Rows(1), 0)
If Err.Number <> 0 Then
MsgBox "Class Pass header was not found", vbCritical, "Action Cancelled"
Exit Sub
End If
On Error GoTo 0
For r = .Cells(.Rows.Count, cpass).End(xlUp).Row To 1 Step -1
If WorksheetFunction.CountA(.Rows(r).Columns("H:L")) = 0 Then .Rows(r).Delete
Next r
.Range("A:L").AutoFilter Field:=6
End With
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
MsgBox ("All Class Passes with no payment have been deleted, and any with a payment have been cleared.")
End Sub