2014-01-29 64 views
0

我的要求是:Excel:在特定列中輸入日期

我想在1月1日至1月31日的E5至AI5列輸入日期。目前使用下面的代碼不工作。

第二年我作爲用戶輸入應該改變每一次。

Sub LoopA() 
    Call Using_InputBox_Method 
    Dim i As Integer 
    Dim j As Integer 
    Dim PH As Integer 
    i = 5 
    For j = 5 To 35 
       Cells(i, j).Value = "=Date(E1,1,j)" 
    Next j 


End Sub 

    Public Function Using_InputBox_Method() As Integer 


     Dim Response As Integer 

    ' Run the Input Box. 
    Response = Application.InputBox("Enter a Year.", _ 
    "Number Entry", , 250, 75, "", , 1) 

    ' Check to see if Cancel was pressed. 
    If Response <> False Then 

    ' If not, write the number to the first cell in the first sheet. 
    Worksheets(1).Range("E1").Value = Response 

    End If 

    Using_InputBox_Method = Response 

End Function 

回答

0

A)

"任何將被視爲一個String。所以"=Date(E1,1,j)"只是一個字符串。你想,我猜是什麼

"=Date(E1,1," & j & ")" 

B)

For j = 5 To 35

您確定要上去,直到35?你可以在任何一個月的上限爲31 :)

=Date()語法是DATE(year,month,day)

你也將需要額外的檢查,在這裏看它是否是一個有效的日期。例如2月30日會給你一個錯誤。

C)

InputBox應避免接受日期。它可能會產生錯誤。您可能需要使用THIS。如果你仍然想使用InputBox那麼你將不得不做驗證,以確保沒有錯誤。

d)

關於中,Year自動改變,你將不得不增加年度在E欄一旦用戶自動進入的日期。

這是你正在嘗試?

Sub Sample() 
    Dim Yr As Long, i As Long 
    Dim ws As Worksheet 

    Set ws = ThisWorkbook.Sheets("Sheet1") 

    Yr = Application.InputBox("Enter a Year.", _ 
    "Number Entry", , 250, 75, "", , 1) 

    '~~> Set it to whatever Year Range you want 
    If Yr < 1900 Or Yr > 9999 Then 
     MsgBox "Incorrect Year" 
     Exit Sub 
    End If 

    With ws 
     .Range("E1").Value = Yr 

     For i = 5 To 35 
      .Cells(5, i).Formula = "=Date(E1,1," & (i - 4) & ")" 
     Next i 
    End With 
End Sub