我在1个excel工作簿中有4个工作表。我试图将Sheet1,Sheet2和Sheet4存储在数组中。然后,我希望程序在第8行中隐藏数组中所有不包含“ FY”值的列。其目的是能够轻松查看FY行,并使Sheet3避免隐藏任何列
这是我的代码段:
Sub FY_HIDE222()
Dim keyCells As Range
Dim ws As Variant
ws = Array("Sheet1", "Sheet2", "Sheet4")
For Each sh In ws
For Each keyCells In ws.Range("C8:ZZ8").Cells
If keyCells.Value <> "FY" Then
keyCells.EntireColumn.Hidden = True
End If
Next keyCells
Next sh
End Sub
我在此行收到语法错误:
For Each keyCells In ws.Range("C8:ZZ8").Cells
说“ keyCells =无” ...请协助我进行思考,因为我认为keyCells变量应存储FY,Q1,Q2等。
答案 0 :(得分:3)
使其尽可能简单
Dim wsName, i As Long, c As Range
wsName = Array("Sheet1", "Sheet2", "Sheet4")
For i = LBound(wsName) To UBound(wsName)
For Each c In Sheets(i).Range("C8:ZZ8")
If c.Value <> "FY" Then c.EntireColumn.Hidden = True
Next c
Next i
答案 1 :(得分:2)
您可以使用联合在同一张纸上收集合格范围,并一口气隐藏。如果您想加倍努力,可以重写该范围的列,并在隐藏整个列的同时退出第一个合格单元格中任何给定列的循环。
Public Sub test()
Dim wsName, i As Long, c As Range, unionRng As Range
wsName = Array("Sheet1", "Sheet2", "Sheet4")
For i = LBound(wsName) To UBound(wsName)
For Each c In Worksheets(wsName(i)).Range("C8:ZZ8")
If c.Value <> "FY" Then
If Not unionRng Is Nothing Then
Set unionRng = Union(unionRng, c)
Else
Set unionRng = c
End If
End If
Next c
If Not unionRng Is Nothing Then
unionRng.EntireColumn.Hidden = True
Set unionRng = Nothing
End If
Next i
End Sub
答案 2 :(得分:1)
变量`sh仅获取字符串值,而不是Worksheet对象。试试
Sub FY_HIDE222()
Dim keyCells As Range
Dim wsName As Variant
Dim ws As Worksheet
wsName = Array("Sheet1", "Sheet2", "Sheet4")
For Each sh In wsName
Set ws = ThisWorkbook.Sheets(sh)
For Each keyCells In ws.Range("C8:ZZ8").Cells
If keyCells.Value <> "FY" Then
keyCells.EntireColumn.Hidden = True
End If
Next keyCells
Next sh
End Sub
答案 3 :(得分:1)
Option Explicit
Sub FY_HIDE222()
Const cStrRange = "C8:ZZ8"
Const cStrText = "FY"
Dim objWs As Worksheet
Dim objCell As Range
Dim vntSheets As Variant
Dim intCounter As Integer
vntSheets = Array("Sheet1", "Sheet2", "Sheet4")
For intCounter = LBound(vntSheets) To UBound(vntSheets)
Set objWs = ThisWorkbook.Worksheets(vntSheets(intCounter))
For Each objCell In objWs.Range(cStrRange)
If objCell.Value <> cStrText Then
objCell.EntireColumn.Hidden = True
End If
Next
Next
End Sub
我有Excel 2003,所以我用Z8代替了ZZ8,这在下图中很明显。
Sub FY_SHOW222()
Dim objWs As Worksheet
Dim vntSheets As Variant
Dim intCounter As Integer
vntSheets = Array("Sheet1", "Sheet2", "Sheet4")
For intCounter = LBound(vntSheets) To UBound(vntSheets)
Set objWs = ThisWorkbook.Worksheets(vntSheets(intCounter))
objWs.Columns.EntireColumn.Hidden = False
Next
End Sub