我如何在第二行中查找内容,如果它不是“白名单”值,则隐藏该列?
我必须浏览具有不同位置列的多个工作表(例如:工作表1名称列为A,工作表2名称列为B)。
编辑:基于@ComradeMicha的评论,我将某些内容放在一起,我确定它是错误的,但是如何使它起作用?
Sub Demo()
Dim arr(2) As String
Dim rng As Range: Set rng = Application.Range("Data!A2:CA2")
Dim cel As Range
arr(0) = "Name"
arr(1) = "Age"
arr(2) = "Gender"
For Each cel In rng.Cells
With cel
If Not IsInArray(cell, arr) Then
Columns(cel).Hidden = True
End If
End With
Next cel
End Sub
Private Function IsInArray(valToBeFound As Variant, arr As Variant) As Boolean
'DEVELOPER: Ryan Wells (wellsr.com)
'DESCRIPTION: Function to check if a value is in an array of values
'INPUT: Pass the function a value to search for and an array of values of any data type.
'OUTPUT: True if is in array, false otherwise
Dim element As Variant
On Error GoTo IsInArrayError: 'array is empty
For Each element In arr
If element = valToBeFound Then
IsInArray = True
Exit Function
End If
Next element
Exit Function
IsInArrayError:
On Error GoTo 0
IsInArray = False
End Function
答案 0 :(得分:1)
如果您只寻找这3个关键字,这应该可以解决问题。它的速度不如检查数组快,但是您并没有遍历那么多列,因此在这里的区别将是微不足道的。
Option Compare Text
删除了文本比较中区分大小写的部分。换句话说,该宏将假设NAME
= name
。
如果没有这个Option
,NAME
<> name
Option Explicit
Option Compare Text
Sub HideColumns()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Data")
Dim MyCell As Range
Dim HideMe As Range
Application.ScreenUpdating = False
For Each MyCell In ws.Range("A2:CA2")
If MyCell = "Name" Or MyCell = "Age" Or MyCell = "Gender" Then
If HideMe Is Nothing Then
Set HideMe = MyCell
Else
Set HideMe = Union(HideMe, MyCell)
End If
End If
Next MyCell
If Not HideMe Is Nothing Then
HideMe.EntireColumn.Hidden = True
End If
Application.ScreenUpdating = True
End Sub
答案 1 :(得分:0)
是的,您需要VBA才能根据值自动隐藏列。
在第2行的每一列中循环浏览(例如,使用:https://www.excel-easy.com/vba/examples/loop-through-defined-range.html),检查单元格值是否在白名单中(例如,使用:https://wellsr.com/vba/2016/excel/check-if-value-is-in-array-vba/),如果不是,则隐藏列:
Columns(i).hidden = true