将公式向下复制x行数

时间:2015-10-08 13:30:05

标签: excel vba

我对此感到茫然,需要一些帮助。我已经潜伏在答案中,并且让Frankensteined合并了一些宏的代码,但它还没有工作。

这是我到目前为止的一部分:

With ActiveSheet
Firstrow = 1
Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
For lrow = Lastrow To Firstrow Step -1
With .Cells(lrow, "G")
    Range("G1").Select
    ActiveCell.FormulaR1C1 = "=IF(ISNUMBER(RC[1]),RC[1],RC[-1])"
End With
Next lrow
End With

我之前有一个非常相似的代码块,可以删除我导入的文本文件中的垃圾,它可以在所有行数中完美运行。当我使用这个公式运行相同的东西时,它只将公式放在G1中,并且不会循环通过表格的其余部分。我已经尝试了这个并且它可以工作,但是复制了所有数百万行:

ActiveCell.FormulaR1C1 = "=IF(ISNUMBER(RC[1]),RC[1],RC[-1])"
Selection.AutoFill Destination:=Range("G:G")

我已经尝试了这个,然后运行相同的代码,摆脱文本文件废话,但我得到一个错误"结束如果没有阻止如果"。

2 个答案:

答案 0 :(得分:1)

要在一个单元格中填充公式,您需要循环使用它们;不要继续依赖ActiveCell property

With ActiveSheet
    Firstrow = 1
    Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
    For lrow = Lastrow To Firstrow Step -1
        .Cells(lrow, "G").FormulaR1C1 = "=IF(ISNUMBER(RC[1]),RC[1],RC[-1])"
    Next lrow
End With

但是你可以通过立即将公式放入所有细胞来加快速度。

With ActiveSheet
    Firstrow = 1
    Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
    With .Range(.Cells(Firstrow, "G"), .Cells(Lastrow, "G"))
        .FormulaR1C1 = "=IF(ISNUMBER(RC[1]),RC[1],RC[-1])"
    End With
End With

有关远离依赖选择和激活以实现目标的更多方法,请参阅How to avoid using Select in Excel VBA macros

答案 1 :(得分:0)

另一个版本,根据标题动态选择列。包括评论。

Dim row As Range
Dim cell As Range
Static value As Integer

'Set row numbers

'Find the starting row. Located using Title of column "Start" plus whatever number of rows.
Dim RowStart As Long
Set FindRow = Range("A:A").Find(What:="Start", LookIn:=xlValues)
RowStart = FindRow.row + 1

'End of the range. Located using a "finished" cell
Dim RowFinish As Long
Set FindRow = Range("A:A").Find(What:="Finished", LookIn:=xlValues)
 RowFinish = FindRow.row - 1

'Set range - Goes Cells(Rownumber, Columnnumber)
'Simply ammend RowStart and RowFinish to change which rows you want.
' In your case you need to change the second column number to paste in horizontally.
Set rng = Range(Cells(RowStart, 1), Cells(RowFinish, 1))
'Start the counter from the starting row.
value = RowStart

For Each row In rng.Rows
  For Each cell In row.Cells

'Insert relevant formula into each cell in range.
cell.Formula = _
"=IF(ISNUMBER(RC[1]),RC[1],RC[-1])"

   'Increment row variable.
    value = value + 1
  Next cell
Next row