2014-05-14 108 views
0

嗨必须比较2个日期变量。 其中之一是从一个普通的字段单元格,我将它存储到一个字符串变量。 另一个来自数据字段,我将它存储到Date变量中。 我按照程序是: -i取第一数据,所述一个在正常的字段是在该格式“(2014年5月8日)”和我在以下过程中进行这项工作:比较格式化日期vba

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

我读了所有的列A与一个for搜索字符串“TIMESTAMP”,并采取相关的日期列旁边。

- 最高日期是最大日期,并且在开始时它从临时日期取值 -countdate是一个变量来计算我想要的日期的数量(我只想在发现的日期更大时计算日期那么本地maximun) -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 

问题是,该过程是不如果内部获取和我有即使在excel表我有几个日期,比第一个,我发现较大阵列上没有元素。 预先感谢您。

+0

OK,时间来学习一些非常基本的像遍历你的代码一样进行调试... –

回答

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

谢谢你,新的改变,它说“数组已经标注尺寸”。 – Andrea

+0

现在,它的工作阵列,我把REDIM PRESERVE之前把数据“在房间里,”听起来不错:)非常感谢。 – Andrea