Excelfile 您好,我有一个带有时间戳的excel文件,如图所示 我要计算差异,然后在新列中输入值。我尝试了以下代码,但显示类型不匹配错误,我不知道为什么。 我知道这很容易,但是我是VBA的新手,所以请帮助我。
\\Sub macro1()
Dim i As Integer
Dim j As Integer
Dim k As Integer
i = 1
j = 2
k = 2
Do While Cells(i, 1).Value <> ""
Cells(k, 2).Value = Cells(j, 1).Value - Cells(i, 1).Value
i = i + 1
j = i + 1
k = i
Loop
End Sub
答案 0 :(得分:1)
在使用CDate将单元格值转换为日期之前,应先处理您的格式(2.10.2017 08:08:30),然后使用VBA函数DateDiff。见下文。将= timeDiff(A2,A1)放在B2中,然后复制到B3中。下面是VBA代码。
Public Function transformCellStrInDate(ByVal rng As Range) As Date
Dim splitArr As Variant, dateArr As Variant, dateStr As String
splitArr = Split(Trim(rng.Value))
dateArr = Split(splitArr(0), ".")
dateStr = dateArr(0) & "/" & dateArr(1) & "/" & dateArr(2) & " " & splitArr(1)
transformCellStrInDate = CDate(dateStr)
Erase dateArr: Erase splitArr
End Function
Public Function timeDiff(ByVal rngY As Range, ByVal rngX As Range) As Long
timeDiff = DateDiff("n", transformCellStrInDate(rngX), transformCellStrInDate(rngY)) / 60 ' in Hours
End Function