Excel:在特定列中输入日期

时间:2014-01-29 06:12:57

标签: excel vba excel-vba

我的要求是:

我想在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

1 个答案:

答案 0 :(得分: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