首页 > 解决方案 > VBA 公式填充一行太远

问题描述

我有这个我正在填充的公式,它在 VBA 中非常简单。我唯一的问题是这个计算实际上走得太远了,在我的下一步中,我将降序排序,从而产生进一步的复合问题。

下面的代码有缺陷吗?

Sub Formz()
    
        With ThisWorkbook.Worksheets("Dinosaurs")
    
            .Cells(2, 9).Resize(.Cells(.Rows.Count, 1).End(xlUp).Row).Formula = "=IF(A2="""","""",ABS(G2))"
            End With
            
 
            
              
End Sub

标签: excelvba

解决方案


定义范围

快速修复

Sub Formz()
    With ThisWorkbook.Worksheets("Dinosaurs")
        .Cells(2, 9).Resize(.Cells(.Rows.Count, 1).End(xlUp).Row - 1).Formula = "=IF(A2="""","""",ABS(G2))"
    End With
End Sub

为什么- 1

  • 因为您的范围不是从第一行开始的。

  • 问题应该是“为什么+ 1?” .

    因为

    Range("A1:A5") = Range("A1:A5).Resize(1, 1)
    

    Range("A1:A5") = Range("A1:A5").Offset(0, 0)            
    

    您将不会使用+ 1.


Sub FormzWhy()
    
    Const FirstRow As Long = 2
    Const Col As Long = 9
    
    With ThisWorkbook.Worksheets("Dinosaurs")
        LastRow = .Cells(.Rows.Count, Col).End(xlUp).Row
        Dim rg As Range
        
        ' Your way:
        Set rg = .Cells(FirstRow, Col).Resize(LastRow - FirstRow + 1)
        Set rg = .Cells(2, 9).Resize(LastRow - 2 + 1)
        Set rg = .Cells(2, 9).Resize(LastRow - 1)
        ' Your attempt was missing the '- 1':
        Set rg = .Cells(2, 9).Resize(.Cells(.Rows.Count, 9).End(xlUp).Row - 1)
        
        ' Ben's way (see in the comments):
        Set rg = .Range(.Cells(FirstRow, Col), .Cells(LastRow, Col))
        Set rg = .Range(.Cells(2, 9), .Cells(.Rows.Count, 9).End(xlUp))
    
    End With
    
    rg.Formula = "=IF(A2="""","""",ABS(G2))"

End Sub
  • 请注意,如果例如第一行是,4那么它将是- 4 + 1 = - 3

推荐阅读