使用值将范围更改为第一个和最后一个列

我的工作文件的一点帮助是赞赏..

下面是我的代码,我想要的是将此公式设置为固定的范围.. Sheets("Unire").Range("CB4:HJ4"))我的意思是范围将从(第4行:Col CB)到第4行的最后一列,并带有值。

 Sub Unire() Dim cell As Range Application.ScreenUpdating = False Sheets("Unire").Activate For Each cell In Intersect(ActiveSheet.UsedRange, Sheets("Unire").Range("CB4:HJ4")) cell.EntireColumn.Hidden = cell.value <> Sheets("Command").Range("B5") And Not IsEmpty(cell) Next cell Application.ScreenUpdating = True End Sub 

如果你的第4行不是空单元格填充“常量”(即不是从公式)值,那么你可以提高你的代码速度迭代只通过不是空白的单元格的手段的方法的SpecialCells()方法的Range对象

此外,你最好存储Sheets("Command").Range("B5").Value帮助variables中的值一劳永逸,而不是每次迭代访问

 Option Explicit Sub Unire() Dim cell As Range Dim refVal As Variant refVal = Sheets("Command").Range("B5").Value '<--| store reference value for subsequent comparisons On Error GoTo ExitSub '<--| make sure to properly exit this sub should sunsequent statements (namely 'SpecialCells' one) raise any error Application.ScreenUpdating = False With Sheets("Unire") For Each cell In .Range("CB4", .cells(4, .columns.Count).End(xlToLeft)).SpecialCells(xlCellTypeConstants) ' <--| reference not empty cells from CB4 to last not-empty cell in row 4 cell.EntireColumn.Hidden = cell.Value <> refVal Next End With ExitSub: Application.ScreenUpdating = True End Sub 

这应该做的:

 Sub Unire() Dim cell As Range Application.ScreenUpdating = False With Sheets("Unire") For Each cell In .Range("CB4", .Range("XFD4").End(xlToLeft)) ' <-- from CB4 to last non-empty on row 4 cell.EntireColumn.Hidden = cell.value <> Sheets("Command").Range("B5").value And Not IsEmpty(cell) Next cell End With Application.ScreenUpdating = True End Sub