数组公式 VIa VBA 应用于空白单元格给出错误

Array Formula VIa VBA Applied to Blank Cells GIving Error

我有一个宏试图检查列以查看是否有任何空白单元格。在任何空白单元格中,我需要放置一个数组公式。

数组公式在 sheet 上运行良好,它是:

=INDEX($CJ:$CJ0,MATCH(1,INDEX(($CL:$CL0=CL2)*($CJ:$CJ0<>""),0),0))

在宏中我不能使用固定范围所以 CJ100 和 CL100 需要是 CL "LastRow" 和 CJ "LastRow" 因为数据范围是动态的。

到目前为止我有这个代码:

Dim ws as worksheet
 Dim LastRow as long
Dim i As Long

set ws = worksheets("Sheet1")

With ws


LastRow = ws.Range("B" & rows.Count).End(xlUp).Row


For i = 1 To LastRow
    If ws.Range("CJ" & i).Value = "" Then


Range("CJ" & i).FormulaArray = "=index(CJ1:CJ ""& LastRow"",MATCH(1,INDEX((CL1:CL ""& LastRow"" = CL ""&i"")*(CJ1:CJ ""& LastRow <>""""),0),0))"

End If
Next i
End With

我在这一行遇到错误:Range("CJ" & i).FormulaArray = "=index(CJ1:CJ ""& LastRow"",MATCH(1,INDEX((CL1:CL ""& LastRow"" = CL ""&i"")*(CJ1:CJ ""& LastRow <>""""),0),0))"

错误是可怕的 "Unable to set the FormulaArray property of the Range class"。

经过一些研究,似乎因为我一次将公式应用于一个单元格,也许我不需要使用 .FormulaArray 我将问题行更改为使用 .formula = "-=.... 但这导致在 "Application defined or object defined error" 条消息中。

我认为问题可能出在我对 range 的使用上,我尝试了以下变体:

Dim LastRow as long
Dim ws as worksheet

set ws = worksheets("Sheet1")

LastRow = ws.Range("B" & rows.Count).End(xlUp).Row
Set rng = ws.Range("CJ2:CJ" & LastRow)

For Each cell In rng
  'test value in column CJ
   If cell.Value = "" Then
        'inserts formula
cell.FormulaArray = "=index(CJ1:CJ ""& LastRow"",MATCH(1,INDEX((CL1:CL ""& LastRow"" = CL2)*(CJ1:CJ ""& LastRow <>""""),0),0))"
'cell.arrayformula
    End If
 Next
End With

这会导致与我在 post 顶部的代码相同的公式数组错误。

我不认为公式超过 250 个字符,除非我计算字符数不正确?也许某处有语法错误?

您对数组公式的实现不正确,并且您也没有正确限定范围引用,因为缺少前面的点。

Range("CJ" & i).FormulaArray = "=index(CJ1:CJ ""& LastRow"",MATCH(1,INDEX((CL1:CL ""& LastRow"" = CL ""&i"")*(CJ1:CJ ""& LastRow <>""""),0),0))"

下面是应该适合您的更新代码:

Sub ApplyArrayFormula()
    Dim ws As Worksheet
    Dim LastRow As Long
    Dim i As Long

    Set ws = Worksheets("Sheet1")

    With ws


    LastRow = .Range("B" & Rows.Count).End(xlUp).Row


        For i = 1 To LastRow
            If .Range("CJ" & i).Value = "" Then
                .Range("CJ" & i).FormulaArray = "=INDEX($CJ:$CJ$" & LastRow & ",MATCH(1,INDEX(($CL:$CL$" & LastRow & "=CL" & i & ")*($CJ:$CJ$" & LastRow & "<>""""),0),0))"
            End If
        Next i
    End With
End Sub