[英]Excel VBA - Iterate Columns and Autofill if Cell Has Formula
Can someone please help me figure out what is wrong with this code? 有人可以帮我找出这段代码有什么问题吗? I am trying to iterate through a database in excel to automatically fill down formulas to the last row.
我正在尝试遍历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
Update: So I think I have figured out a solution. 更新:所以我想我已经找到了解决方案。 I believe the problem was with the Autofill code.
我相信问题出在自动填充代码上。 I switched to copy paste special and it started to work.
我切换到特殊复制粘贴,它开始起作用。 Unfortunately, it was very slow in the beginning.
不幸的是,开始时它非常慢。 After using an array the code ran much faster.
使用数组后,代码运行得更快。 Thanks for the help!
谢谢您的帮助!
I am very new to VBA by the way... 顺便说一下,我是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
It will be faster if you use 如果您使用它将更快
Application.ScreenUpdating = False
at the beginning and 在开始和
Application.ScreenUpdating = true
at the end of the code to avoid excessive screen refresh. 在代码末尾,以避免过多的屏幕刷新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.