我有一个用户窗体,允许用户选择与用户相关的行和列。我正在使用此代码,但是它搜索所有行和所有列,因此不会删除正确的行。谁能提出解决此问题的解决方案,使其适用于行和列?谢谢。
Dim RowToTest As Long
Dim MySheet As Worksheet
Dim ProjectedDate As Date
Dim ColToTest As Long
Dim TempKeep As Integer
TempKeep = 0
ProjectedDate = Date + 60
For Each MySheet In ThisWorkbook.Sheets
For RowToTest = MySheet.Cells(Rows.Count, 1).End(xlUp).Row To 2 Step -1
For ColToTest = MySheet.Cells(2, Columns.Count).End(xlToLeft).Column To 15 Step -1
With MySheet.Cells(RowToTest, ColToTest)
If IsDate(MySheet.Cells(RowToTest, ColToTest).Value) Then
If .Value < ProjectedDate Then
TempKeep = 1
End If
End If
End With
Next ColToTest
If TempKeep = 0 Then
MySheet.Rows(RowToTest).EntireRow.Delete
End If
TempKeep = 0
Next RowToTest
Next
答案 0 :(得分:1)
您可以通过其.Rows
和.Columns
属性检查单元格是否被隐藏,如下所示:
If CelToCheck.Rows.Hidden or CelToCheck.Columns.Hidden Then
'Your code if hidden
Else
'Code if not hidden
End if
在您的情况下,CelToCheck是
MySheet.Cells(RowToTest, ColToTest)
或者,您可以设置范围变量并仅使用
遍历可见单元格For each CL in RangeVariable.SpecialCells(xlCellTypeVisible)
'Your code
Next CL
答案 1 :(得分:1)
我将使用.Hidden
属性建议与JvdV相同。可以在代码中使用如下代码:
Dim RowToTest As Long
Dim MySheet As Worksheet
Dim ProjectedDate As Date
Dim ColToTest As Long
Dim TempKeep As Integer
TempKeep = 0
ProjectedDate = Date + 60
For Each MySheet In ThisWorkbook.Sheets
For RowToTest = MySheet.Cells(Rows.Count, 1).End(xlUp).Row To 2 Step -1
For ColToTest = MySheet.Cells(2, Columns.Count).End(xlToLeft).Column To 15 Step -1
With MySheet.Cells(RowToTest, ColToTest)
If IsDate(MySheet.Cells(RowToTest, ColToTest).Value) Then
If .Value < ProjectedDate Then
TempKeep = 1
End If
End If
End With
Next ColToTest
If TempKeep = 0 and Not isHiddenRow(MySheet, RowToTest) Then
MySheet.Rows(RowToTest).EntireRow.Delete
End If
TempKeep = 0
Next RowToTest
Next
不一定需要具有这样做的功能,但是可以使代码重用更加容易。
Function isHiddenRow(sht As Worksheet, rowNr As Long) As Boolean
On Error Resume Next
isHiddenRow = sht.Rows(rowNr).Hidden
End Function
Function isHiddenCol(sht As Worksheet, colNr As Long) As Boolean
On Error Resume Next
isHiddenCol = sht.Columns(colNr).Hidden
End Function
PS:取决于工作表中有多少数据,通常不建议直接在工作表上循环。如果您有数千行,请考虑使用arrays
。