我正在玩下面的代码示例。
Sub Hide_Columns_Containing_Value()
Dim c As Range
Dim ThisIsToday As Date
Dim TwoWeeksBack As Date
Dim ThreeMonthsAhead As Date
ThisIsToday = Date
TwoWeeksBack = ThisIsToday - 14
ThreeMonthsAhead = ThisIsToday + 100
For Each c In Range("O4:XA4").Cells
If c.Value < TwoWeeksBack Or c.Value > ThreeMonthsAhead Then
Range(c.Address).Select
Selection.ColumnWidth = 1.75
Else
c.EntireColumn.Hidden = True
End If
Next c
End Sub
基本上我想循环遍历所有单元格,如果该值是一个小于2的日期,或者从现在开始超过3个月,我想隐藏该列。问题是日期不在每个单元格中;日期是每7个单元格,代表每个星期五。由于所有空白单元格,隐藏和显示列的工作方式并不像我想要的那样。
以下是日期的截屏。
答案 0 :(得分:2)
这是你想要做的事情
Option Explicit
Public Sub HideColumnsContainingValue()
Dim c As Range
Dim thisIsToday As Date
Dim twoWeeksBack As Date
Dim threeMonthsAhead As Date
thisIsToday = Date
twoWeeksBack = thisIsToday - 14
threeMonthsAhead = thisIsToday + 100
For Each c In Range("O4:XA4").Cells
With c
If Len(.Value2) > 0 Then 'if not empty
If IsDate(.Value) Then 'if date
If .Value < twoWeeksBack Or .Value > threeMonthsAhead Then
.EntireColumn.Hidden = True
Else
.ColumnWidth = 1.75
End If
End If
End If
End With
Next
End Sub
此版本更快一点
Public Sub HideDatesNotInRange()
Dim dateRng As Range, dateArr As Variant
Dim c As Long, minDay As Date, maxDay As Date
minDay = Date - 14
maxDay = Date + 100
Set dateRng = Range("O4:XA4")
dateArr = dateRng 'iterate over array
Application.ScreenUpdating = False
For c = 1 To UBound(dateArr, 2)
If Len(dateArr(1, c)) > 0 Then 'if not empty
If IsDate(dateArr(1, c)) Then 'if date
With dateRng(1, c)
If dateArr(1, c) < minDay Or dateArr(1, c) > maxDay Then
.EntireColumn.Hidden = True
Else
.ColumnWidth = 1.75
End If
End With
End If
End If
Next
Application.ScreenUpdating = True
End Sub
答案 1 :(得分:0)
Sub dostuff()
Dim c As Range
For Each c In Range("A:C").Columns
c.ColumnWidth = 77
Next c
End Sub
你应该可以填写这里的空白