Excel VBA – 迭代列和自动填充,如果单元格有公式
有人可以帮我找出这个代码有什么问题吗? 我想在Excel中迭代通过数据库自动填充公式到最后一行。
Sub AutoFillFormulas() Dim LastRow As Long Dim LastColumn As Long Dim i As Integer LastColumn = ActiveSheet.Cells(3, Columns.Count).End(xlToLeft).Column LastRow = Range("B65536").End(xlUp).Row For i = 1 To LastColumn If Cells(4, i).HasFormula = True Then Cells(4, i).Select Selection.AutoFill Destination:=Range(Cells(4, i), Cells(LastRow, i)), Type:=xlFillDefault End If Next i End Sub
更新:所以我想我已经find了一个解决scheme。 我相信问题出在Autofill代码上。 我切换到复制粘贴特殊,它开始工作。 不幸的是,一开始它的速度很慢。 使用数组后,代码运行得更快。 谢谢您的帮助!
顺便说一下,我对VBA非常陌生
Sub AutoFillFormulas() Application.Calculation = xlCalculateManual Dim LastRow As Long Dim LastColumn As Long Dim i As Integer Dim vData() As Variant LastColumn = ActiveSheet.Cells(3, Columns.Count).End(xlToLeft).Column LastRow = Range("B65536").End(xlUp).Row vData = ActiveSheet.Range(Cells(1, 1), Cells(LastRow, LastColumn)).Value For i = 1 To LastColumn If Cells(4, i).HasFormula = True Then Cells(4, i).Copy Range(Cells(4, i), Cells(LastRow, i)).PasteSpecial xlPasteFormulas End If Next i ActiveSheet.Range(Cells(1, 1), Cells(LastRow, LastColumn)).Value = vData Application.Calculation = xlCalculationAutomatic End Sub
如果你使用它会更快
Application.ScreenUpdating = False
在开始和
Application.ScreenUpdating = true
在代码的最后,以避免过度的屏幕刷新。