Range类的自动填充方法失败:VBA

时间:2014-09-16 17:40:13

标签: excel excel-vba autofill vba

我是VBA的新手,而且我无法理解我的代码落在何处。我收到消息" Range类的自动填充方法失败"在尝试实现If语句之后。

我的代码是:

 Columns("H:H").Select
    ActiveCell.FormulaR1C1 = _
    "=IF(C[-6] = ""Commodities Ags/Softs"", (IF(RC[-3]=R1C24,""Y"",(IF(RC[-3]=R2C24,""Y"",(IF(RC[-3]=R3C24,""Y"",(IF(RC[-3]=R4C24,""Y"",(IF(RC[-3]=R5C24,""Y"",(IF(RC[-3]=R6C24,""Y"",(IF(RC[-3]=R7C24,""Y"",(IF(RC[-3]=R8C24,""Y"",(IF(RC[-3]=R9C24,""Y"",""N"")))))))))))))))))),"""")"
Selection.AutoFill Destination:=Columns("H:H"), Type:=xlFillDefault

它在最后一行失败,If语句没问题,任何帮助都将不胜感激,

干杯

2 个答案:

答案 0 :(得分:1)

这是你在尝试的吗?

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long

    '~~> Change this to the relevant sheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        '~~> Find last row in Col H
        lRow = .Range("H" & .Rows.Count).End(xlUp).Row

        '~~> Enter the formula in one go
        .Range("H1:H" & lRow).FormulaR1C1 = "=IF(C[-6] = ""Commodities Ags/Softs"", " & _
                                            "(IF(RC[-3]=R1C24,""Y"",(IF(RC[-3]=R2C24,""Y""," & _
                                            "(IF(RC[-3]=R3C24,""Y"",(IF(RC[-3]=R4C24,""Y""," & _
                                            "(IF(RC[-3]=R5C24,""Y"",(IF(RC[-3]=R6C24,""Y""," & _
                                            "(IF(RC[-3]=R7C24,""Y"",(IF(RC[-3]=R8C24,""Y""," & _
                                            "(IF(RC[-3]=R9C24,""Y"",""N"")))))))))))))))))),"""")"
    End With
End Sub

答案 1 :(得分:0)

Autofill的工作原理如下:

SingleCell.AutoFill MoreCells

你有

ColumnH.AutoFill ColumnH

如果您想使用自动填充,它可能看起来像这样

With ActiveSheet.Range("H1")
    .FormulaR1C1 = _
    "=IF(C[-6] = ""Commodities Ags/Softs"", (IF(RC[-3]=R1C24,""Y"",(IF(RC[-3]=R2C24,""Y"",(IF(RC[-3]=R3C24,""Y"",(IF(RC[-3]=R4C24,""Y"",(IF(RC[-3]=R5C24,""Y"",(IF(RC[-3]=R6C24,""Y"",(IF(RC[-3]=R7C24,""Y"",(IF(RC[-3]=R8C24,""Y"",(IF(RC[-3]=R9C24,""Y"",""N"")))))))))))))))))),"""")"
    .AutoFill Destination:=.Resize(100, 1), Type:=xlFillDefault
End With

我没有自动填充整个列b / c,这是一百万行,我没有那种时间。

Siddharth的R1C1答案是要走的路,我只是想让你了解Autofill。