我使用以下代码并获取错误。该代码用于获取一组sigle项,并将它们和它们各自的对应值组合在一起。
application-defined or object-defined error
当代码到达该行时:
`.Range(“B15:B”& LastRow).Formula =“= SUMIF(”& myrng1.Address&“,RC [-1],”& myrng2.Address&“)”
错误是代码的中间部分RC[-1]
如果有人可以告诉我我用什么来代替这个,那将是非常有帮助的
`
代码是
Sub InventorySummerise()
Dim LastRow As Long
LastRow = Cells(Rows.Count, "B").End(xlUp).Row
Set myrng1 = Range("B2:B" & LastRow)
Set myrng2 = Range("D2:D" & LastRow)
Cells(LastRow + 5, 2).Select
With ThisWorkbook.Sheets("Sheet1")
.Range("B15:B" & LastRow).Formula = "=SUMIF(" & myrng1.Address & ",RC[-1]," & myrng2.Address & ")"
End With
End Sub
任何有关错误的帮助都会令人惊讶,我会以最后的智慧结束
谢谢!
答案 0 :(得分:4)
完成此任务的两种方法:
<强>一:强>
'~~> change RC[-1] reference to A1 notation
'~~> so if you are putting formula in B15, RC[-1] is A15
With ThisWorkbook.Sheets("Sheet1")
.Range("B15:B" & LastRow).Formula = "=SUMIF(" & myrng1.Address & ",A15," & myrng2.Address & ")"
End With
二:
'~~> As what Patrick said, use FormulaR1C1
'~~> Then change R1C1 address reference style for your ranges
With ThisWorkbook.Sheets("Sheet1")
.Range("B15:B" & LastRow).FormulaR1C1 = "=SUMIF(" & myrng1.Address(ReferenceStyle:=xlR1C1) & ",RC[-1]," & myrng2.Address(ReferenceStyle:=xlR1C1) & ")"
End With
希望这会有所帮助。
答案 1 :(得分:1)
您正在尝试将R1C1公式用于普通公式。
应该使用.Range("B15:B" & LastRow).FormulaR1C1 = "..."
试试这个:
Sub InventorySummerise()
On Error Resume Next
Dim LastRow As Long, myrng1 As Range, myrng2 As Range
LastRow = Cells(Rows.Count, "B").End(xlUp).Row
Set myrng1 = Range("B3:" & Cells(LastRow, 2).Address(rowabsolute:=False, columnabsolute:=False))
Set myrng2 = Range("D3:" & Cells(LastRow, 4).Address(rowabsolute:=False, columnabsolute:=False))
With ThisWorkbook
.Names("Range1").Delete
.Names("Range2").Delete
.Names.Add "Range1", myrng1
.Names.Add "Range2", myrng2
.Sheets("Sheet1").Range("B15:B" & LastRow + 5).Formula = "=SUMIF(Range1,RC[-1],Range2)"
End With
End Sub
答案 2 :(得分:0)
希望它已经为你解决了。如果情况并非如此,则错误来自.range无法识别。如果激活工作簿不打扰您,您可以尝试以下操作:
Sub InventorySummerise()
Dim wtb As Workbook
Dim LastRow As Long
Set wtb = ThisWorkbook
LastRow = Cells(Rows.Count, "B").End(xlUp).Row
Set myrng1 = Range("B3:" & Cells(LastRow, 2).Address(rowabsolute:=False, columnabsolute:=False))
Set myrng2 = Range("D3:" & Cells(LastRow, 4).Address(rowabsolute:=False, columnabsolute:=False))
Cells(LastRow + 5, 2).Select
wtb.Activate
With Sheets("Sheet1")
.Range("B15:B" & LastRow).Formula = "=SUMIF(" & myrng1.Address & ",1," & myrng2.Address & ")"
End With
End Sub