如何在Excel VBA中使用地址功能?

时间:2017-03-29 17:33:34

标签: excel vba excel-vba

我正在尝试使用VBA使用地址函数动态地将公式添加到几个单元格中。当我运行以下脚本时,我会打开一个文件浏览器窗口。我不确定为什么会这样。我做错了什么?

以下是我尝试过的解决方案之一:

Sub AddFormulas()

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(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()

         Else
            'Do some stuff
        End If
    Next i
End Sub

我也试过这个:

Sub AddFormulas()

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(Sheet7.Cells(2, startCount + i)) Then

            Sheet7.Cells(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

2 个答案:

答案 0 :(得分:2)

您是否重命名了工作表?您不能在工作表公式中使用代号,但可以从代号中检索名称。

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

我已经在工作表名称中添加了包装单引号,以防它们包含空格;如果他们不这样做,就没有任何损害。

答案 1 :(得分:2)

我按照以下方式

With Sheet7
    With .Range("CU2")
        colCount = .Range(.Cells, .End(xlToRight)).Columns.Count
    End With

    startCount = 98

    For i = 1 To colCount

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

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

        Else
            'Do some stuff
        End If
    Next i
End With