excel - 如何在 VBA 中的两个变量点之间创建一个范围?
问题描述
我正在尝试编写自动化某些东西的代码:我有一个数据表,我需要在其中添加一列,然后将一个总和放入其中,一直到数据的底行,不再赘述。我知道如何将底行定义为变量;但是如果我输入数据的列也可以变化呢?在我的示例中,我想要进行求和的列始终位于标题为“16”的列的左侧。它总是从第 2 行开始,但并不总是 O 列。例如,它可能是 P 列或 Q 列。
Sub enter_column_and_add_calculations()
Dim NBottomrow
Call find_bottom_row
NBottomrow = ActiveCell.Row
'find column entitled '16':
Range("A1").Select
Cells.Find(What:="16", After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext,
MatchCase:=False _
, SearchFormat:=False).Activate
'insert new column to the left:
Selection.EntireColumn.Insert , CopyOrigin:=xlFormatFromLeftOrAbove
'insert text in the cell:
ActiveCell.FormulaR1C1 = "OOT Debt"
'offset one cell below:
ActiveCell.Offset(1, 0).Range("A1").Select
'i'm now in the cell i want my range to start at. In this example it's cell O2, but it often varies:
ActiveCell.FormulaR1C1 = "=SUM(RC[1]:RC[5])"
Selection.AutoFill Destination:=Range("O2:O" & NBottomrow)
End Sub
Private Sub find_bottom_row()
Range("A1").Select
Selection.End(xlDown).Select
End Sub
非常感谢您的帮助 :-)
解决方案
尝试,
Sub enter_column_and_add_calculations()
dim m as variant, lr as long
with worksheets("sheet1")
m = application.match(16, .rows(1), 0)
if iserror(m) then exit sub
lr = .cells(.rows.count, m).end(xlup).row
.cells(lr+1, m).formula = "=sum(" & .range(.cells(2, m), .cells(lr, m)).address(0,0) & ")"
end with
end sub
推荐阅读
- valgrind - Massif 可视化工具无法在图例中显示文本
- c# - CreateUploadSession 返回“不支持 OData 请求”
- azure - 如何管理 Azure 应用服务证书
- html - 如何将 Google 自定义搜索引擎结果重定向到 results.php 页面?
- javascript - jQuery.Popup 不是构造函数 & 查询未定义(匿名函数)
- kubernetes - 带有 kubernetes 的 traefik-ingress 中注释方法的路由
- c++ - 是否需要为 C++ 编译器安装 X Code?如果我安装 X Code 并卸载它会怎样?g++ 编译器也会被删除吗?
- ms-access - JULIA ODBC.query MethodError:没有匹配每个列的方法
- typescript - Typescript array.map 没有正确分配交集类型
- python - Google GCP提供的python版Dataflow培训课程在哪里