在单元格中输入日期时刷新工作表

问题描述 投票:0回答:1

在 Excel 工作表的上部,我可以通过下拉菜单(单元格 D9)输入两个关键字。我可以在下面输入日期(单元格 D19)。

在 Excel 工作表的下部是由两个关键字分割的十二个月的多个列表。关键字 1 和 2 有多个相同的列表。

我希望当我选择其中一个关键字时,隐藏其他关键字的列表。
此外,我希望列表中隐藏输入日期之前的月份。

ChatGPT 给了我代码。唯一的问题是,当我输入某个日期,然后输入原始日期之前的日期时,工作表不会刷新。

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim iCell As Range
    Dim ws As Worksheet
    Dim dateToCompare As Date
    Dim cell As Range

    Set ws = ThisWorkbook.Sheets("Eingabe") ' Change "Eingabe" to your sheet name
    Set iCell = Intersect(Range("D9"), Target)

    ' Handle "Strom" and "Gas" functionality
    If Not iCell Is Nothing Then
        If iCell.Value = "Strom" Then
            ' Adjust these ranges to match your data
            ws.Rows("23:61").Hidden = False
            ws.Rows("62:100").Hidden = True
        ElseIf iCell.Value = "Gas" Then
            ' Adjust these ranges to match your data
            ws.Rows("23:61").Hidden = True
            ws.Rows("62:100").Hidden = False
        'Else ' do nothing
        End If
    End If

    ' Check for dates in column C and hide rows if the date is earlier than D19
    dateToCompare = ws.Range("D19").Value
    For Each cell In ws.Range("C1:C" & ws.Cells(ws.Rows.Count, "C").End(xlUp).Row)
        If Not cell.EntireRow.Hidden Then ' Check if the row is not already hidden
            If IsDate(cell.Value) And cell.Value < dateToCompare Then
                cell.EntireRow.Hidden = True
            Else
                cell.EntireRow.Hidden = False
            End If
        End If
    Next cell
End Sub
excel vba formatting
1个回答
0
投票

我认为您每次都进行选择然后运行宏,正确吗?你不是设置了自动运行吗?

如果是这种情况..最简单的解决方案可能是制作第二个宏以将页面“重置”回默认值。 (虽然现在我正在写这篇文章,但我认为将其添加到当前宏的开头会更容易 - 但两个单独的宏的逻辑可能使逻辑更容易理解 - 至少对我来说!:-))

用“非技术术语”(我知道您是 VBA 新手)我建议的是...导致您的问题的是:一旦数据以一种方式过滤...某些部分就会卡住,具体取决于关于未来输入的变化。如果在每次输入更改之后(或之前)您将文件“重置”为其原始的、未过滤的版本,这将不是问题!

在您的具体示例中,我认为(可能会丢失某些内容),但唯一要“重置”的是列是否隐藏。

如果您只是添加:

ws.Rows("1:100").Hidden = False

就在您当前评论/行之前:

 ' Handle "Strom" and "Gas" functionality

你应该已经准备好了!

© www.soinside.com 2019 - 2024. All rights reserved.