在VBA中使用字符串变量抛出对象/应用程序错误

时间:2015-08-07 13:28:11

标签: excel vba excel-vba

我得到了一个"应用程序定义的或对象定义的错误"当我尝试将活动工作表中的单元格设置为公式时被抛出。我认为这是由于我试图在公式中使用Sheets.Name函数,请参阅下面的代码:

Public Sub getChannels()
    Dim lastRow As Long
    Dim i As Integer, counter As Integer
    Dim rng As Range, rngB As Range, rngC As Range
    Dim sht As Worksheet

    Dim test As String
    Set sht = Sheets("Summary Sheet - 30-07-2015")
    sht.Activate

    lastRow = sht.Cells(sht.Rows.Count, "B").End(xlUp).Row
    For counter = 1 To lastRow Step 3
        If ActiveSheet.Cells(counter, 12) = "LTE 2C" Then
            ActiveSheet.Cells(counter, 16) = _
                "=INDEX('LTE 2C'!C[55],MATCH(""'"" & sht.name &""'""!RC[-14],'LTE 2C'!C[-11],0))"
            ActiveSheet.Cells(counter, 17) = _
                "=INDEX('LTE 2C'!C[53],MATCH(""'"" & sht.name &""'""!RC[-15],'LTE 2C'!C[-12],0))"
            ActiveSheet.Cells(counter, 18) = _
                "=INDEX('LTE 2C'!C[55],MATCH(""'"" & sht.name &""'""!RC[-16],'LTE 2C'!C[-13],0))"

            Range("P" & counter & ":R" & counter).Select
            Selection.Copy
            Range("P" & counter + 1 & ":P" & counter + 2).Select
            ActiveSheet.Paste
        End If

        Next

End Sub

我错过了一些明显的东西吗?

2 个答案:

答案 0 :(得分:1)

更改您的公式:

ActiveSheet.Cells(counter, 16) = _
    "=INDEX('LTE 2C'!C[55],MATCH(" & "'" & sht.name & "'" & "!RC[-14],'LTE 2C'!C[-11],0))"
ActiveSheet.Cells(counter, 17) = _
    "=INDEX('LTE 2C'!C[53],MATCH(" & "'" & sht.name & "'" & "!RC[-15],'LTE 2C'!C[-12],0))"
ActiveSheet.Cells(counter, 18) = _
    "=INDEX('LTE 2C'!C[55],MATCH(" & "'" & sht.name & "'" & "!RC[-16],'LTE 2C'!C[-13],0))"

答案 1 :(得分:0)

Nelly是正确的,但另一种方法是简单地为每个撇号删除不必要的额外字符串并将其替换为:

ActiveSheet.Cells(counter, 16) = _
"=INDEX('LTE 2C'!C[55],MATCH('" & sht.name & "'!RC[-14],'LTE 2C'!C[-11],0))"

撇号只是在前后连接到弦上。它确实没有区别,但它删除了额外的(&)s。