使用 Excel VBA 根据范围内单元格的值隐藏命名范围

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

我正在开发一个协调多个收银机的程序。每个工作表都有一个针对该月每一天的命名范围,每个范围由 16 行组成。每个命名范围内都有一个包含日期的单元格,格式为“2024 年 1 月 1 日星期三”。

我需要使用 VBA 隐藏所有包含日期的单元格为星期日的命名范围。我希望每次程序运行时都运行这个函数。看起来很简单,根据该范围内的单元格值隐藏一个范围,但由于某种原因,这段代码让我很恼火。

任何帮助将不胜感激。

excel vba named-ranges
1个回答
0
投票

根据您的日期格式,这可能适合您。

每个工作表都有一个名为“JanDateRange”、“FebDateRange”等的命名范围。代码将检查命名范围名称是否包含文本“DateRange”,并且仅对这些范围进行操作。

如果您的日期是实际日期,格式为 “dddd, mmmm d, yyyy” 那么这应该有效:

Public Sub Test()

    Dim NR As Name
    Dim Cell As Range
    For Each NR In ThisWorkbook.Names 'Look at each named range within the workbook.
        If InStr(NR.Name, "DateRange") <> 0 Then 'Check the named range name contains specific text.
        
            'The named range is multiple columns wide, this looks at the cells in the first column.
            'If the named range is only one columns you can omit the .Columns(1).Cells part of the code.
            For Each Cell In NR.RefersToRange.Columns(1).Cells
                If Weekday(Cell, vbSunday) = 1 Then 'Return the day number of the week. Sunday = 1, Saturday = 7
                    Cell.EntireRow.Hidden = True
                End If
            Next Cell
        End If
    Next NR

End Sub  

如果您的日期只是文本,那么这应该有效:

Public Sub Test1()

    Dim NR As Name
    Dim Cell As Range
    For Each NR In ThisWorkbook.Names 'Look at each named range within the workbook.
        If InStr(NR.Name, "DateRange") <> 0 Then 'Check the named range name contains specific text.
        
            'The named range is multiple columns wide, this looks at the cells in the first column.
            'If the named range is only one columns you can omit the .Columns(1).Cells part of the code.
            For Each Cell In NR.RefersToRange.Columns(1).Cells
                If InStr(Cell, ",") <> 0 Then 'Instr will return 0 if there's no comma in the text.
                
                    'Extract the word before the first comma in the text and check if it's "Sunday"
                    If Left(Cell, InStr(Cell, ",") - 1) = "Sunday" Then
                        Cell.EntireRow.Hidden = True
                    End If
                    
                End If
            Next Cell
        End If
    Next NR

End Sub  

话虽如此……首先查看您的代码和一些示例数据将使回答问题变得更加容易。

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