用variables语法replace范围

我正在尝试做一个dynamic范围来sorting我的数据库,我得到了这个代码的最后一行types不匹配错误。 我猜测它来自于我用variablesreplace值的地方。 任何人有关于如何修复语法的提示?

Sub Fake_Code() Dim Row_Limit2 As Long Dim Row_Limit1 As Long Dim Current_Sheet As String Dim r As Range Dim r2 As Range Cells.Find(What:="Title", After:=ActiveCell, LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False).Activate Range(Selection, Selection.End(xlDown)).Name = "Range1" Set r = Range("Range1") Cells.Find(What:="Country", After:=ActiveCell, LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False).Activate Range(Selection, Selection.End(xlDown)).Name = "Range2" Set r2 = Range("Range2") Row_Limit1 = Worksheets(" Branded").Range("X:X").Cells.SpecialCells(xlCellTypeConstants).Count Row_Limit2 = Worksheets(" Branded").Range("Y:Y").Cells.SpecialCells(xlCellTypeConstants).Count 'I need to make all of the below dynamic based on the variables above Worksheets(" Branded").Range("A1").Formula = "=COUNTIFS([" & r & "]: [" & r2 & "],RC2,R21C22:R71C22,R2C)" End Sub 

你的行正在构build一个公式,但是将一个范围传递给它,而不是范围的地址,使用.Address(ReferenceStyle:=xlR1C1 。一旦那里,删除方括号: –

 Worksheets(" Branded").Range("A1").Formula = "=COUNTIFS(" & r.Address(ReferenceStyle:=xlR1C1) & ":" & r2.Address(ReferenceStyle:=xlR1C1) & ",RC2,R21C22:R71C22,R2C)" 

它显示为#value但是我们没有完整的数据集来testing。

我意识到我犯了一个错误。 有了上述答案,我发现它需要。

  Worksheets(" Branded").Range("A1").Formula = "=COUNTIFS(" & r.Address(ReferenceStyle:=xlR1C1) & ",RC2, " & r2.Address(ReferenceStyle:=xlR1C1) & ",R2C)"