Excel VBA - 如果单元格具有公式,则迭代列和自动填充

时间:2014-07-25 18:13:32

标签: excel excel-vba 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

更新:所以我想我已经找到了解决方案。我认为问题在于自动填充代码。我切换到复制粘贴特殊,它开始工作。不幸的是,一开始它很慢。使用数组后,代码运行得更快。谢谢您的帮助!

顺便说一句,我对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

1 个答案:

答案 0 :(得分:0)

如果你使用

会更快
Application.ScreenUpdating = False 

开头和

Application.ScreenUpdating = true

在代码的末尾,以避免过多的屏幕刷新。