VBA将IFERROR写入多个单元格用于…下一个循环

我试图将“= 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 

预先感谢您的帮助!

你可以改为使用.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)variables名。

只需使用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