VBA在看似随意的时间吐出错误?

时间:2017-12-08 16:22:37

标签: excel vba excel-vba

我有一个公式数组,我将填充第2行的所有相关列。之后,我有代码用动态引用填充范围。这个特定的数据集有74行数据,但由于某种原因,接收

  

438错误:'对象不支持此属性或方法'

每次都在第65行。

     'Find last row/col variables
        Dim lastRow As Long
        Dim lastCol As Long
        'Array variable
        Dim TestFormulas() As Variant
       'WS variable
         Dim WS as Worksheet

    lastRow = Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

lastCol = Cells.Find(What:="*", _
                    After:=Range("A1"), LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByColumns, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

'Create Array [this is cut down significantly. There are roughly 50 formulas here. Code runs quickly, if it matters.]
TestFormulas() = Array( _
                  "=Sheet1!H2", "=Sheet1!B2", "=IF(Sheet1!P2=""Resiliency""") 

'Fill Row 2 with formulas
 With WS
    For i = LBound(TestFormulas()) To UBound(TestFormulas())
      .Cells(2, 1 + i).Formula = TestFormulas(i)
    Next i
 End With

'Copy formulas and fill down the entire range 
 Range("A2:" & lastCol & ":" & "2").Formula = TestFormulas
 Range("A2:" & WS(1).lastCol & ":" & WS(1).lastRow).FillDown

我期待范围填充动态公式。它充满了动态,尽管只有第65行。

  

438错误:'对象不支持此属性或方法'

1 个答案:

答案 0 :(得分:1)

Dim lastRow As Long

'Array variable
Dim TestFormulas() As Variant
'WS variable
Dim WS As Worksheet

Set WS = Worksheets("Sheet4") ' change to your sheet name

With WS
    If Application.WorksheetFunction.CountA(Worksheets("Sheet1").Cells) > 0 Then
        lastRow = Worksheets("Sheet1").Cells.Find(What:="*", _
            After:=Range("A1"), _
            LookAt:=xlPart, _
            LookIn:=xlFormulas, _
            SearchOrder:=xlByRows, _
            SearchDirection:=xlPrevious, _
            MatchCase:=False).Row


        'Create Array [this is cut down significantly. There are roughly 50 formulas here. Code runs quickly, if it matters.]
        TestFormulas() = Array( _
        "=Sheet1!H2", "=Sheet1!B2", "=IF(Sheet1!P2=""Resiliency"",TRUE,FALSE)")

        'Fill Row 2 with formulas

        For i = LBound(TestFormulas()) To UBound(TestFormulas())
            .Range(.Cells(2, 1 + i), .Cells(lastRow, 1 + i)).Formula = TestFormulas(i)
        Next i
    End If
End With