【问题标题】:Excel-VBA : FillDown not working when sheet has an AutoFilter applied & row containing calculations is hidden by filter settingsExcel-VBA:当工作表应用了自动筛选并且包含计算的行被筛选设置隐藏时,FillDown 不起作用
【发布时间】: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 留空,但会将计算应用于所有可见行。因此,任何隐藏的行都留空,并更新可视行以包含计算。至于“调整大小”功能的建议,那太好了,我相信我将来可以使用它来让事情变得更容易。
  • 道歉 - 我忘记了那个可憎的事(雷德蒙德的某个人需要为此而努力)。应用过滤器后,恐怕您必须遍历单元格。

标签: vba excel


【解决方案1】:

解决方法可能是先将不可见的第 2 行复制到可见的第 3 行末端,然后向下填充。比如:

Range(Cells(2, LastCol + 1),Cells(2,lastcolaftercalculations)).copy Range(Cells(3, LastCol + 1,Cells(2,lastcolaftercalculations))
Range(Cells(3, LastCol + 1), Cells(LastRow, lastcolaftercalculations)).FillDown

但这不会填充其他过滤的单元格。如果您希望可以使用this 代码,它将首先禁用自动过滤器,然后在您运行代码后将其重置为之前的设置。

【讨论】:

  • Marco,谢谢您 - 确定、存储和重新应用原始自动过滤器设置的代码很有效,并且解决了我的问题。非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-18
  • 1970-01-01
相关资源
最近更新 更多