【发布时间】:2016-04-27 15:13:53
【问题描述】:
我有下面的代码,它非常适合我的目的,除非自动过滤器应用于工作表并且第 2 行被自动过滤器隐藏。
宏将“Record_Created_Year”和“=Year(##)”正确插入第一个空列和第 1/2 行(即使该行被隐藏),但不会将计算填充到最后一行。
不是填写添加到第 2 行的计算,而是选择第 2 个可见行(可能是第 3 行)并填写这些单元格中的值(这些单元格是空白的,但出于测试目的,我将它们填充到证明理论)。
我已经能够通过包含命令“ActiveSheet.AutoFilterMode = False”来解决此问题,但是这会导致部分用户在运行宏后需要重新应用复杂的过滤器时出现一些问题。
是否有更好的方法来定义 FillDown 范围,因此它会忽略自动过滤器并实际上填充 Row2 中的数据/计算,而不是第二个可见行中包含的数据?
为任何帮助提前欢呼。
Private Sub Add_and_Filldown_Calcs()
Dim LastCol As Long
With ActiveSheet
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
Dim LastRow As Long
With ActiveSheet
LastRow = .Cells(Rows.Count, 1).End(xlUp).Row
End With
Dim rng As Range
Set rng = ActiveSheet.Cells
Dim Created_Date As Range
Set Created_Date = ActiveSheet.Range("A1:BZ1").Find("sys_created_on", lookat:=xlWhole)
rng.Parent.Cells(1, LastCol + 1).Value = "Record_Created_Year"
rng.Parent.Cells(2, LastCol + 1).Formula = "=year(" & Replace(Created_Date.Address(False, False), "1", "") & "2)"
rng.Parent.Cells(1, LastCol + 2).Value = "Record_Created_Month"
rng.Parent.Cells(2, LastCol + 2).Formula = "=Month(" & Replace(Created_Date.Address(False, False), "1", "") & "2)"
' Many others removed to make it easier to read
'Filldown new calcs
Dim LastColAfterCalulations As Long
With ActiveSheet
lastcolaftercalculations = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
Range(Cells(2, LastCol + 1), Cells(LastRow, lastcolaftercalculations)).FillDown
End Sub
【问题讨论】:
-
您最初可以填充所有行:
rng.Parent.Cells(2, LastCol + 1).Resize(lastrow - 1).Formula = ...等等。 -
罗里,谢谢你的建议。我已经尝试过了,它改变了输出但是并没有完全解决这个问题。当行被隐藏时,原始计算不会添加到 Row2 中,而是将 Row2 留空,但会将计算应用于所有可见行。因此,任何隐藏的行都留空,并更新可视行以包含计算。至于“调整大小”功能的建议,那太好了,我相信我将来可以使用它来让事情变得更容易。
-
道歉 - 我忘记了那个可憎的事(雷德蒙德的某个人需要为此而努力)。应用过滤器后,恐怕您必须遍历单元格。