【发布时间】:2022-07-01 05:51:01
【问题描述】:
我试图从“数据转储”表中复制一个日期并将其粘贴到“每日累积”中的最后一行。但是,数据转储中的日期格式交换了年份和月份,因此已更正。它还包括一个我希望删除的时间戳,以便我可以在它旁边的单元格中运行 vlookup。我当前的解决方案添加一列并运行 excel 函数将时间戳设置为 00:00:00,以便工作日、期间和周格式起作用。出于某种原因,我的代码错误地设置了继续粘贴的日期,不知道如何解决这个问题,谢谢!
为了更清晰,附上了当前和所需输出的屏幕截图。 此外,如果有一种方法可以在不添加列的情况下剪切并粘贴时间戳,那就更好了。在空间宏之后尝试了一些删除,但无法让它们中的任何一个工作。
复制日期的宏
Sub CopyDate()
Dim ws1 As Worksheet: Set ws1 = Worksheets("Data Dump")
Dim ws2 As Worksheet: Set ws2 = Worksheets("Daily Cumulations")
ws1.Activate 'otherwise have to be in Data Dump sheet to run the macro?
Dim TakeDate As String
Dim lastrow As Long
lastrow = ws2.Range("G" & Cells.Rows.Count).End(xlUp).row
' Two different versions from LM
' First is 2006-14-21 for June 14 2021
' Second is 6/14/21 for June 14 2021
'**First version
If InStr(Range("G4").Value, "-") <> 0 Then
Dim strFull As String
strFull = Range("G4").Value
Dim month As String
Dim dd As String
Dim yyyy As String
Dim c As Variant
month = Split(strFull, "-")(0)
month = Right(month, 2)
dd = Split(strFull, "-")(1)
yyyy = Split(strFull, "-")(2)
TakeDate = month + "-" + dd + "-" + yyyy
MsgBox TakeDate
ws2.Range("G" & lastrow + 1).Value = TakeDate
'**second version?
Else
TakeDate = Format(Range("G4").Value, "yyyy/mm/dd")
End If
End Sub
重置时间戳的宏
Sub TrimDate()
Dim cl As Variant
Dim ws2 As Worksheet: Set ws2 = Worksheets("Daily Cumulations")
Dim lastrow As Long
lastrow = ws2.Range("G" & Cells.Rows.Count).End(xlUp).row
Dim TrimDate As Range
Set TrimDate = ws2.Range("H2:H" & lastrow)
TrimDate.Formula = "=DATEVALUE(TEXT(G2,""yyyy-mm-dd""))"
End Sub
要复制到最后一行的宏
Sub CopyDateDown()
Dim ws As Worksheet: Set ws = Worksheets("Daily Cumulations")
Dim StartRow As Long
Dim EndRow1 As Long: EndRow1 = ws.Cells(ws.Rows.Count, 5).End(xlUp).row
Dim EndRow2 As Long: EndRow2 = ws.Cells(ws.Rows.Count, 7).End(xlUp).row
With ws
If Application.WorksheetFunction.CountA(.Columns(7)) <> 0 Then
StartRow = .Cells(Rows.Count, "G").End(xlUp).row + 1
Else
StartRow = 2
End If
Dim i As Integer
For i = StartRow To EndRow1
ws.Cells(i, 7).Value = EndRow2
Next i
End With
End Sub
【问题讨论】:
-
不要在 Excel 中将日期保存或输出为字符串。它将尝试解释字符串并可能翻转您的月份和日期。一旦你有了
month、dd和yyyy变量,使用DateSerial创建一个真正的Date变量。如果将其输出到工作表上,则没有歧义,Excel 不会翻转日期和月份。 -
你可能也有一些运气,只是直接用
CDate转换为日期,比如`ws2.Range("G" & lastrow + 1).Value = CDate(Range("G4").Value) -
数据转储表是从另一个应用程序中提取的。对于上面的示例,日期是 2022 年 4 月 11 日,在 excel 中,日期为 2004-11-22。这就是我将其转换为字符串的原因。我不熟悉 DateSerial 所以我不知道我是否可以应用它?
-
将该字符串放入
CDate。它将能够正确地将其转换为日期。
标签: excel vba date datetime-format