[英]Excel VBA - Iterate Columns and Autofill if Cell Has Formula
有人可以幫我找出這段代碼有什么問題嗎? 我正在嘗試遍歷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
如果您使用它將更快
Application.ScreenUpdating = False
在開始和
Application.ScreenUpdating = true
在代碼末尾,以避免過多的屏幕刷新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.