比较格式化日期vba

时间:2014-05-14 13:51:39

标签: excel vba

你必须比较2个日期变量'。 其中一个来自一般的现场单元,我将它存储到一个String变量中。 另一个是从数据字段中获取的,并将其存储到Date变量中。 我遵循的程序是: -i获取第一个数据,即正常字段中的数据,格式为“(5-8-2014)”,我按以下步骤处理:

tempdate1 = Cells(27, "N").Value:
tempdate1 = Replace(tempdate1, "(", ""):
tempdate1 = Replace(tempdate1, ")", ""):
tempdate1 = Format(tempdate1, "DD-MM-YYYY"):

我读了所有A列,用for来搜索字符串“TIMESTAMP”并在其旁边取相关的日期列。

- 最高日期是最大日期,并且在开始时它从tempdate获取值 -countdate是一个变量来计算我想要的日期数量(我只想在我找到的日期大于本地最大值时计算日期) -if temp> date1我发现了一个本地MAXIMUM,我计算了TIMESTAMP,并在数组中输入了日期。

 highestDate = tempdate1
countdate = 1 ' because i have already the first date
k = 0
dates(k) = highestDate ' i put in the first position the first data
'Find the highest Date
For i = 1 To lastRow
If Cells(i, 3).Value = "TIMESTAMP" Then
temp = Cells(i, 4).Value:
temp = Format(temp, "MM-DD-YYYY"):
date1 = CDate(highestDate):
    If temp > date1 Then: date1 = temp: countdate = countdate + 1: highestDate = date1:
dates(k) = highestDate: k = k + 1
End If
Next i

问题是该过程没有进入if并且我在阵列上没有元素,即使在excel表中我有几个日期大于我找到的第一个日期。 提前谢谢。

1 个答案:

答案 0 :(得分:1)

虽然VBA允许冒号,连续字符,但通常不推荐。例如,使用冒号时很难调试,因为您无法设置断点。

请在

上设置断点
   dates(k) = highestDate

调试时,您会看到它是如何设置数组的边界的:

dim dates(0)
highestDate = tempdate1
countdate = 1 ' because i have already the first date
k = 0
dates(k) = highestDate ' i put in the first position the first data
'Find the highest Date
For i = 1 To lastRow
If Cells(i, 3).Value = "TIMESTAMP" Then
temp = Cells(i, 4).Value:
temp = Format(temp, "MM-DD-YYYY"):
date1 = CDate(highestDate):
    If temp > date1 Then: date1 = temp: countdate = countdate + 1: highestDate = date1:
        dates(k) = highestDate 
        k = k + 1
        REDIM PRESERVE dates(k) 'make room in the array!
    End If
Next i
相关问题