我是VBA的新手,正在编写代码,使用大量的"if“语句通过公式插入数量可变的新行。行插入工作得很好,但是我很难插入公式。我目前正在用类似于下面的代码插入行:
Sub InsertRow()
'Establish variable for search range
Dim i As Range
Dim cell As Range
Set i = Range("B:B")
For Each cell In i.Cells
'Manual input for conductor count search and insert amount below
If cell.Value = "4-1/C" Then
cell.Offset(1).EntireRow.Resize(3).Insert
End If
Next
End Sub我的问题是:A列中的值直接引用了我想引用单元格的选项卡名(例如,A1应该是"Sheet2“)。我想在Sheet1上的R列中插入一个公式,以便从Sheet2上的单元格A22中提取值。对于剩余的插入列,我想从Sheet2插入A23,从Sheet2插入A24,等等。下面是我正在尝试做的图像。我已经隐藏了不适用的列。https://i.stack.imgur.com/pqiUy.jpg
我一直在尝试使用偏移量和RC-2函数,但无可否认,我非常迷茫。使用excel间接函数(而不是VBA),我可以用= indirect ("'"&$A$1&"'!A22")来获取这些值,但是我不能在VBA中完成。
提前感谢您的帮助
发布于 2018-11-28 05:43:41
根据截图假设引用,并对所有内容进行硬编码:
Range("R1").Formula = "=INDIRECT(""'""&A1&""'!A22"")"
Range("R1:R8").FillDown发布于 2018-11-28 21:51:49
我想通了。我试着用.Formula而不是.Value,我也不知道宏录制器。谢谢Bruce为我指明了正确的方向。结果代码只需要为我的所有行插入"IF“语句进行循环:
Sub test()
Dim x As Long
Dim firstRow As Long
firstRow = 1
Dim lastRow As Long
With ActiveSheet
lastRow = .Range("B2").End(xlDown).Row
For x = lastRow To firstRow Step -1
If .Range("B" & x).Value = "4-1/C" Then
.Range("B" & x).Offset(0, 15).Value = "=INDIRECT(""'""&RC[-16]&""'!A22"")"
.Range("B" & x).Offset(1, 15).Value = "=INDIRECT(""'""&R[-1]C[-16]&""'!A23"")"
.Range("B" & x).Offset(2, 15).Value = "=INDIRECT(""'""&R[-2]C[-16]&""'!A24"")"
.Range("B" & x).Offset(3, 15).Value = "=INDIRECT(""'""&R[-3]C[-16]&""'!A25"")"
.Range("B" & x).Offset(0, 16).Value = "=INDIRECT(""'""&RC[-17]&""'!J22"")"
.Range("B" & x).Offset(1, 16).Value = "=INDIRECT(""'""&R[-1]C[-17]&""'!J23"")"
.Range("B" & x).Offset(2, 16).Value = "=INDIRECT(""'""&R[-2]C[-17]&""'!J24"")"
.Range("B" & x).Offset(3, 16).Value = "=INDIRECT(""'""&R[-3]C[-17]&""'!J25"")"
End If
Next
End With
End Subhttps://stackoverflow.com/questions/53503165
复制相似问题