【问题标题】:VBA - How To Loop Over Sets Of Fiscal Year DatesVBA - 如何循环财政年度日期集
【发布时间】:2020-01-08 20:35:05
【问题描述】:

在 Excel VBA 中循环财政年度日期时遇到问题。

我的目标:隐藏日期大于今天的列。

我的问题:这些列是按会计年度组织的(我比日历年提前 6 个月)。因此,下面的代码并不像我想要的那样。

Sub Hide_Date_Columns()
Dim c As Range

For Each c In Range("F2:AC2").Cells
    If c.Value > Date Then
        Columns(c.column).EntireColumn.Hidden = True
    End If
Next c

End Sub

我试图通过在我的 for 循环中添加 x = DateAdd("yyyy", 1, (Range("R2:W2").Value)) 来解决这个问题,但是我得到了一个类型不匹配.

Sub Hide_Date_Columns()
Dim a As Range
Dim b As Variant
Dim c As Range
Dim DateArray() As Variant
Dim x() As Variant
Dim i As Variant
x = DateAdd("yyyy", 1, (Range("R2:W2").Value))
b = Range("R2:W2")

For Each a In Range("F2:Q2").Cells
    If a.Value > Date Then
        Columns(a.Column).EntireColumn.Hidden = True
    End If
Next a


For Each b In x
    If b.Value > x Then
    Columns(b.Column).EntireColumn.Hidden = True
    End If
Next b


For Each c In Range("R2:AC2").Cells
    If c.Value > Date Then
        Columns(c.Column).EntireColumn.Hidden = True
    End If
Next c

End Sub

任何帮助将不胜感激。

【问题讨论】:

  • 您将需要迭代范围,您不能将 DateAdd 与多个值一起使用。
  • 要说范围本身不支持该方法或属性lol
  • 该死的大声笑。将尝试您的建议并进行报告。
  • 手动完成...下面发布代码。有没有更好的方法?
  • @Hutch 是的,有一种更好的方法可以做到这一点,但它需要输入更多内容。使用数组,然后存储需要隐藏的列(在变量或数组中),然后一次隐藏所有内容。

标签: excel vba


【解决方案1】:

对于任何想知道的人。我手动添加了所需的每个 DateAdd。

Sub Hide_Date_Columns()
Dim a As Range
Dim b As Range
Dim c As Range
Dim d As Range
Dim e As Range
Dim f As Range
Dim g As Range
Dim h As Range

u = DateAdd("yyyy", -1, (Range("R2").Value))
v = DateAdd("yyyy", -1, (Range("S2").Value))
w = DateAdd("yyyy", -1, (Range("T2").Value))
x = DateAdd("yyyy", -1, (Range("U2").Value))
y = DateAdd("yyyy", -1, (Range("V2").Value))
Z = DateAdd("yyyy", -1, (Range("W2").Value))

For Each a In Range("F2:Q2").Cells
    If a.Value > Date Then
        Columns(a.column).EntireColumn.Hidden = True
    End If
Next a

For Each b In Range("X2:AC2").Cells
    If b.Value > Date Then
        Columns(b.column).EntireColumn.Hidden = True
    End If

Next b

If u > Date Then
Columns(u.Columns).EntireColumn.Hidden = True
End If

If v > Date Then
Columns(v.Columns).EntireColumn.Hidden = True
End If

If w > Date Then
Columns(w.Columns).EntireColumn.Hidden = True
End If

If x > Date Then
Columns(x.Columns).EntireColumn.Hidden = True
End If

If y > Date Then
Columns(y.Columns).EntireColumn.Hidden = True
End If

If Z > Date Then
Columns(Z.Columns).EntireColumn.Hidden = True
End If

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多