将Excel公式复制到多张工作表的最后一行
我有一个工作簿,其中有多个名称不同的工作表,但每个工作表的内容结构保持不变。 只有一个表名永远是不变的。
我试图在单元格N2
应用一个公式,然后将公式复制到所有工作表中的最后一个活动行,除了一个名为pie
的代码我迄今为止的代码适用于一个循环,但随后出现错误“AutoFill method范围类失败“我用过
Lastrow = Range("M" & Rows.Count).End(xlUp).Row
确定最后一行,因为列M始终是完整的。 任何帮助来完成这将是非常赞赏我的代码是:
Sub ConcatForm() Dim wSht As Worksheet Lastrow = Range("M" & Rows.Count).End(xlUp).Row Application.ScreenUpdating = False For Each wSht In Worksheets If wSht.Name <> "Pie" Then wSht.Range("N2").FormulaR1C1 = "=CONCATENATE(RC[-3],RC[-2],RC[-1])" wSht.Range("N2").AutoFill Destination:=Range("N2:N" & Lastrow) End If Next wSht Application.ScreenUpdating = True End Sub
你只是一个远离目标的参照:
Sub ConcatForm() Dim wSht As Worksheet lastRow = Range("M" & Rows.count).End(xlUp).row '<--| without explicit worksheet qualification it will reference a range in the "active" sheet Application.ScreenUpdating = False For Each wSht In Worksheets If wSht.Name <> "Pie" Then wSht.Range("N2").FormulaR1C1 = "=CONCATENATE(RC[-3],RC[-2],RC[-1])" wSht.Range("N2").AutoFill Destination:=wSht.Range("N2:N" & lastRow) '<--| this will reference a range in 'wSht' worksheet End If Next Application.ScreenUpdating = True End Sub
您不需要使用Autofill
来实现这一点。
- 只需将您的公式直接应用于您的范围,并使用相对引用 (即
K2
,而不是绝对引用(即$K$2
。 它会填写并更新你的公式。 - 确保您完全符合您的参考资格。 例如,看看我在哪里使用了
ThisWorkbook
和lastrow
如何初始化的更新。 否则,Excel可能会感到困惑并抛出其他错误。 - 你的
lastrow
variables没有被lastrow
所以它是一个隐含的Variant
。 你最好把它定义为一个Long
。
Sub ConcatForm() Application.ScreenUpdating = False Dim wSht As Worksheet Dim lastrow As Long With ThisWorkbook.Worksheets("Sheet1") 'which worksheet to get last row? lastrow = .Range("M" & .Rows.Count).End(xlUp).Row End With For Each wSht In ThisWorkbook.Worksheets If wSht.Name <> "Pie" Then wSht.Range("N2:N" & lastrow).Formula = "=CONCATENATE(K2,L2,M2)" End If Next wSht Application.ScreenUpdating = True End Sub
使用下面的子…
Sub ConcatForm() Dim wSht As Worksheet Lastrow = Range("A" & Rows.Count).End(xlUp).Row Application.ScreenUpdating = False For Each wSht In Worksheets With wSht If .Name <> "Pie" Then .Select .Range("N2").FormulaR1C1 = "=CONCATENATE(RC[-3],RC[-2],RC[-1])" .Range("N2").AutoFill Destination:=Range("N2:N" & Lastrow) End If End With Next wSht Application.ScreenUpdating = True End Sub