简体   繁体   English

使用 VBA 复制/粘贴日期

[英]Copy/Paste Date using VBA

I am trying to insert the date using the Today Function in Excel.我正在尝试在 Excel 中使用 Today Function 插入日期。 I have a sheet with the date at the top, in Cell I2.我在单元格 I2 中有一张日期在顶部的表格。

I have a table and am using VBA to copy paste values into it - this will be used daily and I want the date to be auto populated into Column D, starting from the last used row in Column D and ending with the last used row in Column C.我有一个表,正在使用 VBA 将粘贴值复制到其中 - 这将每天使用,我希望将日期自动填充到 D 列,从 D 列中最后使用的行开始,以最后使用的行结束列 C。 I then want the date to be saved as value.然后我希望将日期保存为值。

I tried using the following code but it didn't work - nothing happened.我尝试使用以下代码,但它没有用 - 什么也没发生。

Can someone please help me understand why, and how to correct this?有人可以帮我理解为什么,以及如何纠正这个问题吗?

With ThisWorkbook
    With .Sheets("Test")
        Dim rng As Range
        Set rng = .Range(.Cells(.Rows.Count, "D").End(xlUp), .Cells(.Rows.Count, "C").End(xlUp).Offset(0, 1))
        
        rng.Value = ThisWorkbook.Sheets("Test").Range("I2").Value
    End With
End With

I believe this is what you want:我相信这就是你想要的:

  1. Find the last used row with Column C ( Assumes the last row in C & D are equal so just calculate this in one column. It looks like you are trying to over-complicate )使用Column C查找最后使用的行(假设 C 和 D 中的最后一行是相等的,所以只需在一列中计算。看起来你试图过于复杂
  2. Skip the temp rng assignment and apply the value transfer using a combination of Offset when calculating lr and Resize when referencing the target row跳过 temp rng分配并在计算lr时使用Offset和在引用目标行时使用Resize组合应用值传输

Sub Try_Me()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Test")
Dim lr As Long

lr = ws.Range("C" & ws.Rows.Count).End(xlUp).Offset(1).Row
ws.Range("C" & lr).Resize(1, 2).Value = ws.Range("I2").Value

End Sub

Looking at your current Set rng =... statement it looks like you may be trying to determine the last used row in either column indicating that the last used row in both may vary.查看您当前的Set rng =...语句,您可能正在尝试确定任一列中最后使用的行,这表明两者中最后使用的行可能会有所不同。 If that is the case, you can compare both and pick the max like so:如果是这种情况,您可以比较两者并选择最大值,如下所示:

Sub Try_Me()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet2")
Dim c As Long, d As Long, lr As Long

c = ws.Range("C" & ws.Rows.Count).End(xlUp).Offset(1).Row
d = ws.Range("C" & ws.Rows.Count).End(xlUp).Offset(1).Row

lr = Application.WorksheetFunction.Max(c, d)
ws.Range("C" & lr).Resize(1, 2).Value = ws.Range("I2").Value

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM