如何使用VBA将动态公式添加到单元格引用?

如何使用VBA将动态公式添加到单元格引用?,vba,excel,Vba,Excel,我正在尝试使用VBA将动态公式添加到单元格中。我在上面看到了一些帖子,但我不知道我做错了什么。我收到一个运行时错误“1004”,原因是对象的“方法”“范围”“工作表”“失败”。我做错了什么 Sub AddFormulas() Dim LastNumberRow As Integer Set countBase = Sheet7.Range("CU2") colCount = Sheet7.Range(countBase, countBase.End(xlToRight)).Columns.C

我正在尝试使用VBA将动态公式添加到单元格中。我在上面看到了一些帖子,但我不知道我做错了什么。我收到一个运行时错误“1004”,原因是对象的“方法”“范围”“工作表”“失败”。我做错了什么

Sub AddFormulas()

Dim LastNumberRow As Integer

Set countBase = Sheet7.Range("CU2")
colCount = Sheet7.Range(countBase, countBase.End(xlToRight)).Columns.Count

Dim startCount As Integer
startCount = 98

    For i = 1 To colCount

        If IsNumeric(Cells(2, startCount + i)) Then
            Sheet7.Range(3, i).Formula = "=Sheet6!" & Cells(3, startCount + i).Address & "*" & "Sheet7!" & Cells(3, colCount + startCount).Address          
        Else
            'Do some stuff
        End If
    Next i
End Sub
我已经从下面的评论中添加了建议的更改,但是我没有得到一个文件浏览器弹出窗口。我已通过以下更改更改了我的代码:

If IsNumeric(Sheet7.Cells(2, startCount + i)) Then
            Set bSum = Sheet7.Cells(3, colCount + startCount)
            Set bSpr = Sheet6.Cells(3, startCount + i)

            Sheet7.Cells(3, i).Formula = "=Sheet6!" & bSpr.Address() & "*" & "Sheet7!" & bSpr.Address()

尝试替换
Sheet7.范围(3,i).公式=…

使用:
Sheet7.单元格(3,i).公式=…

我使用此解决方案使其工作:

Sub Formulas()
'Adds the formulas to the worksheet

Dim rLastCell As Range

Set countBase = Sheet6.Range("CU2")

'Starts at cell CU2 and counts the number of columns to the right that are being used
colCount = Sheet6.Range(countBase, countBase.End(xlToRight)).Columns.Count


Dim startCount As Integer
startCount = 98 'This is column CT

    For i = 1 To colCount

        'Checks to see if the value in row 2 starting at CU is a number, if it is it adds the index-match formula
        If IsNumeric(Sheet7.Cells(2, startCount + i)) Then
            bSpr = Sheet6.Cells(3, startCount + i).Address(True, False)

            Sheet6.Cells(3, startCount + i).Formula = "=INDEX(ORIG_MAT_DATA_ARRAY,MATCH($W3,MAT_RLOE_COLUMN),MATCH(" _
            & bSpr & ",MAT_CY_HEAD))" & "/" & "INDEX(ORIG_MAT_DATA_ARRAY,MATCH($W3,MAT_RLOE_COLUMN),MATCH(""Total"",ORIG_MAT_CY_HEAD,0))"

        End If

        'Checks to see if the value in row 2 starting at CU is the word "Total", if it is it adds the sum formula
        If Sheet6.Cells(2, startCount + i) = "Total" Then
            startCol = Cells(3, startCount + 1).Address(False, False)
            endCol = Cells(3, startCount + (colCount - 1)).Address(False, False)

            Sheet6.Cells(3, colCount + startCount) = "=SUM(" & startCol & ":" & endCol & ")"
        End If
    Next i

End Sub

Sheet7.范围(3,i).公式
应该是
Sheet7.单元格(3,i).公式
为此,请确保您在IsNumeric()中引用了正确的工作表:
Sheet7.单元格(2,startCount+i)
Sheet6.单元格(2,startCount+i)
另外,您希望使用哪张工作表
单元格(3,startCount+i)
单元格(3,colCount+startCount)
要启用吗?您也应该在这之前添加工作表名称/索引,比如对于
Sheet7.Range()
@BruceWayne,因为OP只返回这些坐标处单元格的字符串地址,所以单元格所在的工作表并不重要。@ScottCraner-啊,是的,很好!