Excel VBA: writing formula in current selection
I want to write the current month based on a referenced cell into the current selection. This is my code but I get the error message: object variable or with block variable not set. I don't know what the problem is - anyone have a clue?
Sub SelectionMonthNames()
Dim Currentrange As Range
For i = 1 To 3
Currentrange = Selection.Address
If i = 1 Then
Currentran开发者_JS百科ge.Formula = "=DATE(YEAR($B$5);MONTH($B$5);DAY($B$5))"
Else
Currentrange.Formula = "=DATE(YEAR($B$5);MONTH($B$5)+" & CStr(i - 1) & ";DAY($B$5))"
End If
Selection.Offset(0, 1).Select
Next i
End Sub
Try
Set Currentrange = Selection.Address
Instead of
Currentrange = Selection.Address
EDIT:
So, final version of your macro should look like this:
Sub SelectionMonthNames()
Dim Currentrange As Range
For i = 1 To 3
Set Currentrange = Selection
If i = 1 Then
Currentrange.Formula = "=DATE(YEAR($B$5),MONTH($B$5),DAY($B$5))"
Else
Currentrange.Formula = "=DATE(YEAR($B$5),MONTH($B$5)+" & CStr(i - 1) &",DAY($B$5))"
End If
Selection.Offset(0, 1).Select
Next i
End Sub
精彩评论