我在excel表格中有以下格式的数据:
ItemCode DeliveryDate 5456987 24.01.2009 5456988 5456989 12.24.2009 5456990 12/24/2009
我已将DeliveryDate的值存储在数组中。我需要对日期的基础做出决定,然后将结果打印在新的表格中。所以我必须将值转换为数组:
Dim current as Date, highest as Date, result() as Date
For Each itemDate in DeliveryDateArray
current = CDate(itemDate)
if current > highest then
highest = current
end if
' some more operations an put dates into result array
Next itemDate
'After activating final sheet...
Range("A1").Resize(UBound(result), 1).Value = Application.Transpose(result)
不幸的是,CDate()函数会抛出错误:
运行时错误'13':
类型不匹配
VBA中是否有一个功能可以:
修改
要重现错误,只需运行即可
myDate = CDate("24.01.2009")
答案 0 :(得分:11)
尝试使用Replace
查看它是否适合您。上面提到过几次上面提到的问题是CDate函数在这些时期窒息。您可以使用replace将它们更改为斜杠。要回答有关vba中可以解析任何日期格式的函数的问题,没有任何选项非常有限。
Dim current as Date, highest as Date, result() as Date
For Each itemDate in DeliveryDateArray
Dim tempDate As String
itemDate = IIf(Trim(itemDate) = "", "0", itemDate) 'Added per OP's request.
tempDate = Replace(itemDate, ".", "/")
current = Format(CDate(tempDate),"dd/mm/yyyy")
if current > highest then
highest = current
end if
' some more operations an put dates into result array
Next itemDate
'After activating final sheet...
Range("A1").Resize(UBound(result), 1).Value = Application.Transpose(result)
答案 1 :(得分:0)
看起来它可能会在空数据行上抛出错误,您是否尝试在运行CDate()函数之前确保itemDate不为空?我想这可能是你的问题。
答案 2 :(得分:0)
我使用了这段代码:
ws.Range(“A:A”)。FormulaR1C1 =“= DATEVALUE(RC [1])”
列A将为mm / dd / yyyy
RC [1]是B列,TEXT字符串,例如01/30/12,这不是日期类型