excel - 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
解决方案
定义范围
快速修复
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
。
推荐阅读
- python - 如何摆脱嵌套json中的反斜杠
- azure - Application Insights 在哪里将 HttpContext 注入 IHttpContextAccessor.Request?
- python - Pyfirmata Arduino:无法打开端口(串行异常)
- python - 如何在 Pandas 中将 0 和 1 的空值和非空值计算为行索引而不是 False 和 True
- python - 使用 Python 从 JSON 中删除条目
- java - 如何在 onCreate() 作为输入接收器时解决“非静态与静态”问题
- c# - NUnit TestFixtures 不适用于 RestSharp
- moqui - POPC 采购订单流程
- python - 如何从 python 中的 JSON 字典中删除额外的统计平均结果?
- scrapy - 从亚马逊上删除超过 5,000 条评论