0

I am trying to find month of a date in column A and paste the result to column B. They both have headers, column A’s is Date and column B’s is Month. I would like to have vba codes simply calculating the month of column A.

Here are my codes so far,

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

But I keep getting AutoFill method of range class failed error and I tried to change the AutoFill type but it won’t work. If you guys know a faster way to do it, let me know, too. (not excel functions, plz)

enter image description here

Thank you,

sc1324
  • 590
  • 1
  • 15
  • 36

2 Answers2

1

This code will fail if the value of lastrow is 2. You need to add some logic to account for that. Also revised to use 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
Community
  • 1
  • 1
David Zemens
  • 53,033
  • 11
  • 81
  • 130
0

"The destination must include the source range". Refer the link. So please select the cell. If you want to apply formula to cell use .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
Mukul Varshney
  • 3,131
  • 1
  • 12
  • 19