问题描述
我设法使它起作用,但是问题是我必须指定范围(在这种情况下,我只是对C2:c25进行了硬编码,并且文件每次都有不同的行计数。
是否有一种方法可以仅对具有数据的行运行此操作?
Sub addFormulas()
ThisWorkbook.Worksheets("Sheet2").Range("C2").Formula = "=(B2/12)*100"
Range("C2").Select
Selection.AutoFill Destination:=Range("C2:C25")
End Sub
解决方法
您可以使用xlDown来查找基于B列的最后一行,因此下次无需更改代码。
Sub addFormulas()
ThisWorkbook.Worksheets("Sheet2").Range("C2").Formula = "=(B2/12)*100"
Range("C2").Select
'find last row with value
last_row = Range("B2").End(xlDown).Row
Selection.AutoFill Destination:=Range("C2:C" & last_row)
End Sub
但是我假设B列的值之间没有空白单元格。如果B列中可能有空白单元格,则可以运行FOR循环以查找最后一行。它的效率要低得多,但是只要您没有太多的行,它就可以很好地工作:
Sub addFormulas2()
ThisWorkbook.Worksheets("Sheet2").Range("C2").Formula = "=(B2/12)*100"
Range("C2").Select
For i = 1 To 20
If Range("B" & i) & "" > "" Then last_row = i
Next i
Selection.AutoFill Destination:=Range("C2:C" & last_row)
End Sub
编辑:刚刚了解到,使用xlUp ir比FOR更有效,并且比xlDown更可靠,因为如果B列中有一些空白单元格,则不会有任何问题:
Sub addFormulas_()
ThisWorkbook.Worksheets("Sheet2").Range("C2").Formula = "=(B2/12)*100"
Range("C2").Select
With Sheets("Sheet2")
last_row = .Range("B" & .Rows.Count).End(xlUp).Row
End With
Selection.AutoFill Destination:=Range("C2:C" & last_row)
End Sub
,
您可以不使用AutoFill
或Select
来完成任务。最好使用With … End With
语句。注释在下面的代码中提供。
Sub addFormulas()
With ThisWorkbook.Worksheets("Sheet2") 'used to set the focus on the worksheet object
.Cells(2,3).Resize(.Cells(.Rows.Count,2).End(xlUp).Row - 1).Formula = "=(B2/12)*100"
'writes the formula in the variable range in column C
'Breakdown...
'the "." (dot) e.g. (.Cells and .Rows) is used to refer to the worksheet object in the With statement
'".Cells(2,3)" is the start of the range you want to write the formula
'".Resize(.Cells(.Rows.Count,2).End(xlUp).Row")expands the range to the last use row in column B
'the "- 1" adjusts your range because you started on row 2
End With
End Sub