我正在尝试创建一个代码,该代码可隐藏除两个单元格定义的范围之外的几列。这是代码:
For i = 1 To LastDate
If DDS(1, i) = StartDate Then
DDS.Cells(1, i).EntireColumn.Hidden = False
For j = i To LastDate
If DDS(1, i) = EndDate Then
i = j
Exit For
End If
Next j
Else
DDS.Cells(1, i).EntireColumn.Hidden = True
End If
Next i
有没有办法改善此代码? 尝试隐藏列时为什么会出现对象错误?
“ DDS”是先前定义的范围。
With ActiveSheet
LastDate = .Cells("2", Columns.Count).End(xlToLeft).Column
DDS = Range(.Cells(2, 11), .Cells(56, LastDate))
End With
谢谢。
答案 0 :(得分:0)
尝试
With ActiveSheet
LastDate = .Cells("2", Columns.Count).End(xlToLeft).Column
set DDS = .Range(.Cells(2, 11), .Cells(56, LastDate))
End With
答案 1 :(得分:0)
您可以找到开始日期和结束日期,然后隐藏所有列,并取消隐藏开始日期和结束日期之间的列。
编辑为套件
Sub Button1_Click()
Dim rng As Range
Dim StartDate As Date
Dim EndDate As Date
Dim fDate As Range
Dim e As Range, s As Range, UnH As Range
StartDate = Range("W2").Value
EndDate = Range("X2").Value
Set rng = Rows(1).SpecialCells(xlCellTypeConstants, 23)
Set s = rng.Find(StartDate, lookat:=xlWhole)
Set e = rng.Find(EndDate, lookat:=xlWhole)
Set UnH = Range(Cells(1, s.Column), Cells(1, e.Column))
rng.EntireColumn.Hidden = True
UnH.EntireColumn.Hidden = False
End Sub
答案 2 :(得分:0)
您可以尝试这样。
Sub test()
Dim Ws As Worksheet
Dim DDS As Range
Dim i As Long, j As Long, LastDateCol As Long
Set Ws = ActiveSheet
With Ws
LastDateCol = .Cells("2", Columns.Count).End(xlToLeft).Column
Set DDS = .Range(.Cells(2, 11), .Cells(56, LastDateCol))
End With
For i = 1 To DDS.Columns.Count
If DDS.Item(1, i) = StartDate Then
DDS.Item(1, i).EntireColumn.Hidden = False
For j = i To LastDate
If DDS.Item(1, i) = EndDate Then
i = j
Exit For
End If
Next j
Else
DDS.Item(1, i).EntireColumn.Hidden = True
End If
Next i
End Sub
是否打算只循环第一行(DDS(1, i)
)?
您的范围是55行DDS = Range(.Cells(2, 11), .Cells(56, LastDate))