我正在制作一个模板,该模板将在列update
的每个单元格中包含一个公式,我的同事可以将该公式复制到他的工作表中。为此,我放置了一个可变的行号以使其在同事的工作环境中正常工作。
C
我希望进入For i = 2 To x
Sheets("Worksheet").Range("C" & i).FormulaR1C1 = _
"=INDEX('S2.0 - Setup'!B:I,MATCH(INDIRECT(""C"" & ROW()),'S2.0 - Setup'!I:I,0),1)"
Next
:
C2
但是结果是:
=INDEX('S2.0 - Setup'!B:I);MATCH(INDIRECT("C" & ROW());'S2.0 - Setup'!I:I;0);1)
因此Excel将这些括号放在=INDEX('S2.0 - Setup'!B:(I);MATCH(INDIRECT("C" & ROW());'S2.0 - Setup'!I:(I);0);1)
和B:I
范围内。
答案 0 :(得分:-2)
Sub VBAtoExcelFormula()
Const cVntSource As String = "S2.0 - Setup" ' Source Worksheet Name/Index
Const cVntTarget As String = "Worksheet" ' Target Worksheet Name/Index
Const cStrFirstColumn As String = "B" ' Source First Column Letter
Const cStrLRColumn As String = "I" ' Source Last Row Column Letter
Const cStrFormula As String = "C" ' Target Formula Column Letter
Dim i As Long ' Row Counter
Dim lngLastRow As Long ' Source/Target Last Row
Dim strFormula As String ' Formula String
With Sheets(cVntSource)
lngLastRow = .Cells(.Rows.Count, cStrLRColumn).End(xlUp).Row
End With
For i = 2 To lngLastRow
strFormula = "=INDEX('" & cVntSource & "'!" & cStrFirstColumn _
& ":" & cStrLRColumn & ",MATCH(INDIRECT(""" & cStrFormula _
& """&ROW()),'" & cVntSource & "'!" & cStrLRColumn _
& ":" & cStrLRColumn & ",0),1)"
Debug.Print strFormula
Sheets(cVntTarget).Cells(i, cStrFormula).Formula = strFormula
Next
End Sub
Sub VBAtoExcelFormulaShort()
Const cVntLRColumn As Variant = "I" ' Source Last Row Column Letter/Number
Dim i As Long ' Row Counter
Dim lngLastRow As Long ' Source/Target Last Row
Dim strFormula As String ' Formula String
With Sheets("S2.0 - Setup")
lngLastRow = .Cells(.Rows.Count, cVntLRColumn).End(xlUp).Row
End With
For i = 2 To lngLastRow
strFormula = "=INDEX('S2.0 - Setup'!B:I,MATCH(INDIRECT(""C""&ROW()),'" _
& "S2.0 - Setup'!I:I,0),1)"
Debug.Print strFormula
Sheets("Worksheet").Cells(i, "C").Formula = strFormula
Next
End Sub