请帮忙 - 我已经搜索了几个小时,但没有成功! 我正在使用 Power Query 从 SQL 脚本中获取结果。每次我打开电子表格时,此信息都会更新。信息更新后,我想删除 C 列中日期大于今天的行,这样它们就不会在我的另一张表上的 VLOOKUP 中计算。 我尝试了以下方法:
Private Sub Workbook_Open()
Dim LR As Long, I As Long
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
LR = Range("C" & Rows.Count).End(xlUp).Row
For I = LR To 1 Step -1
If Range("C" & I).Value > Date Then Rows(I).Delete
Next I
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
但这不会自动运行,当手动运行时,它会给出“运行时错误‘1004’:应用程序定义或对象定义的错误”,然后继续删除不正确的日期。
我也试过这个,但它也会删除不正确的日期并给我运行时错误。
Sub DeleteCells()
Dim LR As Long, I As Long
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
LR = Range("C" & Rows.Count).End(xlUp).Row
For I = LR To 1 Step -1
If Range("C" & I).Value > Date Then Rows(I).Delete
Next I
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
最佳答案
编辑 4/11:我猜测 1004 错误的发生是因为所有“Branch Not Open”行之前都已被删除。下面更新的代码在自动筛选步骤周围包装了一个 if
语句,现在只有在筛选范围内找到至少一个“Branch Not Open”的匹配项时才会应用该语句。希望这个版本有效!
@SickDimension 有了一个良好的开端——但由于您知道许多行将在“实时日期”列中列出“Branch Not Open”,您可以使用 autofilter 快速删除它们
。试试这段代码(也更新了 LR
代码):
Private Sub Workbook_Open()
Dim LR As Long, LC As Long, I As Long
Dim FilterRng As Range
Dim DataSheet As Worksheet
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'assign worksheet to save time in references
Set DataSheet = ThisWorkbook.Worksheets("Clocking Exceptions")
'Define your filter range as the block of data
LC = DataSheet.Range("A3").End(xlToRight).Column
With DataSheet
LR = .Range("C" & .Rows.Count).End(xlUp).Row
End With
Set FilterRng = Range(DataSheet.Cells(3, 1), DataSheet.Cells(LR, LC))
'autofilter the sheet to remove "Branch Not Open" rows
If Not FilterRng.Find(What:="Branch Not Open", LookIn:=xlValues, LookAt:=xlWhole) Is Nothing Then
With FilterRng
.AutoFilter Field:=3, Criteria1:="Branch Not Open", Operator:=xlAnd
.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
End With
DataSheet.AutoFilterMode = False
End If
For I = LR To 1 Step -1
If IsDate(DataSheet.Range("C" & I).Value) Then
If DateValue(DataSheet.Range("C" & I).Value) > DateValue(Date) Then Rows(I).Delete
End If
Next I
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
关于excel - 后台查询运行后使用 VB 删除行 - Excel 2010,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22957178/