VBA使用For ... Next循环将IFERROR写入多个单元

时间:2017-05-02 21:29:22

标签: excel vba excel-vba

我正在尝试申请" = IFERROR"到包含超过1000行数据的电子表格。我已经想出了一种方法来使条目硬编码。但有没有办法用像#" = IFERROR(IFERROR(A1,B1),"")"而不是价值?以下是硬编码版本:

Sub HardCodeIFERROR()             
    Dim a As Integer, xRecordCount1 As Integer
    Set w(1) = Sheets("ABC")
    xRecordCount1 = w(1).Cells(Rows.Count, 1).End(xlUp).Row

    For a = 1 To xRecordCount1

        w(1).Cells(a, 3).Value = Application.WorksheetFunction.IfError(Application.WorksheetFunction.IfError(Range("A" & a), Range("B" & a)), "")

        Next a
    Exit Sub


End Sub

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

您只需使用.Formula

即可

w(1).Cells(a, 3).Formula = "=IFERROR(IFERROR(A" & a & ",B" & a & "),"""")"

请注意,您可以跳过循环并只使用范围:

Sub HardCodeIFERROR()
Dim ws1 As Worksheet
Dim a As Integer, xRecordCount1 As Integer
Set ws1 = Sheets("Sheet1")
xRecordCount1 = ws1.Cells(ws1.Rows.Count, 1).End(xlUp).Row

With ws1
    .Range(.Cells(1, 3), .Cells(xRecordCount1, 3)).FormulaR1C1 = "=IFERROR(IFERROR(RC[-2],RC[-1]),"""")"
End With

End Sub

注意:确保在您使用时使用Rows.Count表单,就像使用Cells()Range()一样。此外,我更改了工作表名称,因为我不确定您是否打算使用工作表数组,因此我使用了更清晰(IMO)的变量名称。

答案 1 :(得分:1)

只需使用Formula属性:

Sub HardCodeIFERROR()             
    Dim a As Integer, xRecordCount1 As Integer
    'Need to declare the size of the array if you are going to assign worksheets to "w(1)"
    Dim w(1 To 1) As Worksheet
    Set w(1) = Sheets("ABC")
    'Ensure you fully qualify "Rows.Count" by specifying which worksheet you are referring to
    xRecordCount1 = w(1).Cells(w(1).Rows.Count, 1).End(xlUp).Row
    'Apply formula to all cells
    w(1).Range("C1:C" & xRecordCount1).Formula = "=IFERROR(IFERROR(S1,V1),"""")"
End Sub