将日期列递增 VBA excel
Increment date column by VBA excel
如果我在 excel 中有一列,格式如下:
"dd/mm/yyyy hh:mm:ss" 我想将小时值增加 1。
我将 1/24 添加到该单元格并完成。
我的问题是我需要更正的文件大约有 15000 行,操作大约需要 2 分钟。
我使用的代码是:
Set rngSel = .Range("A2:A10000")
For Each cell In rngSel
cell.Value = cell.Value + dif / 24
Next cell
是否有可能以某种方式更快地完成它?
你可以试试:
Option Explicit
Sub test()
Dim arr As Variant
Dim Initial_DateTime As Date
Dim i As Long
With ThisWorkbook.Worksheets("Sheet1")
arr = .Range("A2:A10000")
For i = LBound(arr) To UBound(arr)
Initial_DateTime = arr(i, 1)
arr(i, 1) = DateAdd("h", 1, Initial_DateTime)
Next i
.Range("A2:A1000").Value = arr
End With
End Sub
如评论中所述,将范围加载到矩阵中并处理内存中日期的递增要快得多。我在您的代码的基础上构建了以下示例。
Sub IncrementDateColumnByVBA()
Dim rngSel As Range
Dim DateArray() As Variant
Dim i As Long
Dim dif As Byte
dif = 1
Set rngSel = ActiveSheet.Range("A2:A10")
'Write range to a matrix
DateArray = rngSel.Value
'Loop matrix
For i = LBound(DateArray) To UBound(DateArray)
DateArray(i, 1) = DateArray(i, 1) + dif / 24
Next i
'Write matrix to worksheet
rngSel.Value = DateArray
End Sub
如果我在 excel 中有一列,格式如下: "dd/mm/yyyy hh:mm:ss" 我想将小时值增加 1。 我将 1/24 添加到该单元格并完成。
我的问题是我需要更正的文件大约有 15000 行,操作大约需要 2 分钟。 我使用的代码是:
Set rngSel = .Range("A2:A10000")
For Each cell In rngSel
cell.Value = cell.Value + dif / 24
Next cell
是否有可能以某种方式更快地完成它?
你可以试试:
Option Explicit
Sub test()
Dim arr As Variant
Dim Initial_DateTime As Date
Dim i As Long
With ThisWorkbook.Worksheets("Sheet1")
arr = .Range("A2:A10000")
For i = LBound(arr) To UBound(arr)
Initial_DateTime = arr(i, 1)
arr(i, 1) = DateAdd("h", 1, Initial_DateTime)
Next i
.Range("A2:A1000").Value = arr
End With
End Sub
如评论中所述,将范围加载到矩阵中并处理内存中日期的递增要快得多。我在您的代码的基础上构建了以下示例。
Sub IncrementDateColumnByVBA()
Dim rngSel As Range
Dim DateArray() As Variant
Dim i As Long
Dim dif As Byte
dif = 1
Set rngSel = ActiveSheet.Range("A2:A10")
'Write range to a matrix
DateArray = rngSel.Value
'Loop matrix
For i = LBound(DateArray) To UBound(DateArray)
DateArray(i, 1) = DateArray(i, 1) + dif / 24
Next i
'Write matrix to worksheet
rngSel.Value = DateArray
End Sub