2011-08-25 90 views
0

我想根據引用的單元格將當前月份寫入當前選擇。這是我的代碼,但我得到錯誤消息:對象變量或未設置塊變量。我不知道問題是什麼 - 任何人都有線索?Excel VBA:在當前選擇中編寫公式

Sub SelectionMonthNames() 

Dim Currentrange As Range 

For i = 1 To 3 

    Currentrange = Selection.Address 

    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 

回答

2

嘗試

Set Currentrange = Selection.Address 

而不是

Currentrange = Selection.Address 

編輯:

所以,在宏的最終版本應該是這樣的:

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 
+0

+1範圍是一個對象,需要設置,不像其他變量。 – Fionnuala

+0

嗨,現在我得到所需的對象,它在這一行中斷。 – user366121

+1

@ user366121好的,Selection.Address是文本,所以使用Selection。 – Fionnuala