我试图在列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但是我不断得到range类的AutoFill方法失败的错误,并且我试图改变AutoFill类型,但是它不起作用。如果你们知道更快的方法,也让我知道。(不是excel函数,plz)

谢谢,
发布于 2016-11-03 22:46:10
如果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发布于 2016-11-03 22:48:34
“目标必须包含源范围”。请参阅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 Subhttps://stackoverflow.com/questions/40404194
复制相似问题