vba范围类的自动填充方法失败

时间:2016-11-03 14:31:16

标签: excel vba

我试图在A列中找到一个日期的月份并将结果粘贴到B列。它们都有标题,A列是日期,B列是月。我想让vba代码只计算A列的月份。

到目前为止,这是我的代码,

Sub Month()
Dim ws As Worksheet
Dim lastrow As Long
Set ws = Worksheets("Sheet1")
ws.Cells(2, "B") = "=Month(A2)"
lastrow = Range("A" & Rows.Count).End(xlUp).Row
Range("B2").AutoFill Destination:=Range("B2:B" & lastrow), Type:=xlFillDefault
End Sub

但是我一直收到范围类失败的自动填充方法错误,我试图更改自动填充类型但它不起作用。如果你们知道更快的方法,请告诉我。 (不是excel功能,PLZ)

enter image description here

谢谢,

2 个答案:

答案 0 :(得分:1)

如果lastrow的值为2,则此代码将失败。您需要添加一些逻辑来说明这一点。还修改为使用better method of finding "last row"

Sub month()
Dim ws As Worksheet
Dim lastrow As Long
Dim startCell As Range

Set ws = Worksheets("sheet1")
With ws
    Set startCell = .Cells(2, 2) ' or .Range("B2")
    lastrow = startCell.EntireColumn.Find("*", AFter:=startCell, SearchDirection:=xlPrevious).Row
    If lastrow = startCell.Row Then lastrow = lastrow + 1
    startCell.Formula = "=Month(A2)"
    startCell.AutoFill Range(startCell, startCell.Cells(lastrow)), xlFillDefault
End With
End Sub

答案 1 :(得分:0)

“目的地必须包含来源范围”。请参阅link。所以请选择单元格。如果要将公式应用于单元格使用.Formula = "=Month(A2)"

Sub Month()
    Dim ws As Worksheet
    Set ws = Worksheets("Sheet1")
    ws.Cells(2, "B") = "=Month(A2)"
    ws.Cells(2, "B").Select
    Selection.AutoFill Destination:=Range("B2:B" & Cells(Rows.Count, "B").End(xlUp).Row), Type:=xlFillDefault
End Sub