Date添加适当的日期变量识别

时间:2013-06-07 16:26:52

标签: vba excel-vba excel

所以我已经仔细研究了这段代码,花了4个小时摆弄它,从头开始重写。我唯一能做到的就是将代码从大约15行减少到现在的9行。

无论如何,代码的问题在于它无法使用intArrayIndex-1正确识别arrDateTime日期。而不是正常日期说“2013年6月7日”,我可以在k = 0 if语句中检索,它返回“1899年12月30日”,我读到的日期声明不正确。

另外,我尝试使用特定的数字来测试它们并且它在j = 0部分没有问题,但是,由于某种原因,j = 1语句不起作用。我也试过通过在DateAdd变量中使用1-j而不是1来简单地修改代码,但是它不想添加任何天。

'grabs date and time
If (k = 0) Then
    intDay = Cells(intRowNum + 2, 2).Value
    arrDateTime(intArrayIndex) = DateValue(strMonth & " " & intDay & ", " & intYear) + (Cells(intRowNum + intMaxRows + 3, 1).Value)
ElseIf j = 0 Then
    arrDateTime(intArrayIndex) = DateAdd("d", 1, arrDateTime(intArrayIndex - 1))
ElseIf j = 1 Then
    arrDateTime(intArrayIndex) = arrDateTime(intArrayIndex - 1)
End If

我在这里绝望,在弄清楚为什么日期变量被错误使用的任何帮助都将非常感激。

更新1

根据要求,我绝对包含了与问题相关的每一段代码,我没有包含所有内容,因为它长达400多行。

Dim intRowNum As Integer
Dim intMaxRows As Integer
Dim intArrayIndex As Integer
Dim intYear As Integer
Dim intDay As Integer
Dim strMonth As String

Dim arrTitle(0 To 9) As String
Dim arrDescription(0 To 9) As String
Dim arrProf(0 To 9) As String
Dim arrDateTime(9) As Date

For j = 0 To 1
     For k = 0 To 4
        intArrayIndex = k * 2 + j

        'grabs date and time
        If (k = 0) Then
            intDay = Cells(intRowNum + 2, 2).Value
            arrDateTime(intArrayIndex) = DateValue(strMonth & " " & intDay & ", " & intYear) + (Cells(intRowNum + intMaxRows + 3, 1).Value) 
        ElseIf j = 0 Then
            arrDateTime(intArrayIndex) = DateAdd("d", 1, arrDateTime(intArrayIndex - 1))
        ElseIf j = 1 Then
            arrDateTime(intArrayIndex) = arrDateTime(intArrayIndex - 1)
        End If

    Next
Next

For j = 0 To 9

    ActiveSheet.Cells(3 + j, 1).Value = j + 1
    ActiveSheet.Cells(3 + j, 5).Value = TimeValue(arrDateTime(j))
    ActiveSheet.Cells(3 + j, 6).Value = MonthName(month(arrDateTime(j)))
    ActiveSheet.Cells(3 + j, 7).Value = Day(arrDateTime(j))
    ActiveSheet.Cells(3 + j, 8).Value = Year(arrDateTime(j))

Next

1 个答案:

答案 0 :(得分:0)

您的迭代如下:

Turn   j    k    intArrayIndex    arrDateTime(intArrayIndex)
   1   0    0                0    is created your date on first array position
   2   0    1                2    arrDateTime(2 -1) does not exist, it is empty/zero!!

因此尝试用你所拥有的东西将1天加零。