简体   繁体   English

excel宏中的今天日期

[英]Today`s date in an excel macro

I am trying to add today's date to column A in sheet2.我正在尝试将今天的日期添加到 sheet2 的 A 列。 Each time my macro pastes my selection in sheet1, column B, to a new row in sheet2.每次我的宏将我在 sheet1、B 列中的选择粘贴到 sheet2 中的新行。

My script works to add the new row and paste my selection in sheet2, but I can't figure out how I should get the date in column A for the new row in sheet2.我的脚本用于添加新行并将我的选择粘贴到 sheet2 中,但我无法弄清楚我应该如何获取 sheet2 中新行的 A 列中的日期。 Here is the script in my macro;这是我的宏中的脚本;

Sub move()  
        Dim i As Integer 
        Application.ScreenUpdating = False
        ActiveWorkbook.Sheets("Sheet1").Range("A1,A2,A3,A4,A5").Copy
       
        Sheets("Sheet2").Select
        i = 3
        While Range("B" & i).Value <> ""
            i = i + 1
        Wend
        Range("B" & i).Select
   
        Selection.PasteSpecial (xlValues), Transpose:=True
 
        Worksheets("Sheet1").Range("A1:A5").Clear
 
End Sub

Try the Date function.试试Date函数。 It will give you today's date in a MM/DD/YYYY format.它将以 MM/DD/YYYY 格式为您提供今天的日期。 If you're looking for today's date in the MM-DD-YYYY format try Date$ .如果您正在寻找 MM-DD-YYYY 格式的今天日期,请尝试Date$ Now() also includes the current time (which you might not need). Now()还包括当前时间(您可能不需要)。 It all depends on what you need.这一切都取决于你需要什么。 :) :)

Here's an example that puts the Now() value in column A.这是一个将Now()值放在 A 列中的示例。

Sub move()
    Dim i As Integer
    Dim sh1 As Worksheet
    Dim sh2 As Worksheet
    Dim nextRow As Long
    Dim copyRange As Range
    Dim destRange As Range

    Application.ScreenUpdating = False

        Set sh1 = ActiveWorkbook.Worksheets("Sheet1")
        Set sh2 = ActiveWorkbook.Worksheets("Sheet2")
        Set copyRange = sh1.Range("A1:A5")

        i = Application.WorksheetFunction.CountA(sh2.Range("B:B")) + 4

        Set destRange = sh2.Range("B" & i)

        destRange.Resize(1, copyRange.Rows.Count).Value = Application.Transpose(copyRange.Value)
        destRange.Offset(0, -1).Value = Format(Now(), "MMM-DD-YYYY")

        copyRange.Clear

    Application.ScreenUpdating = True

End Sub

There are better ways of getting the last row in column B than using a While loop, plenty of examples around here.有比使用While循环更好的方法来获取 B 列的最后一行,这里有很多例子。 Some are better than others but depend on what you're doing and what your worksheet structure looks like.有些比其他更好,但取决于您在做什么以及您的工作表结构是什么样的。 I used one here which assumes that column B is ALL empty except the rows/records you're moving.我在这里使用了一个,它假设 B 列除了您要移动的行/记录外都是空的。 If that's not the case, or if B1:B3 have some values in them, you'd need to modify or use another method.如果不是这种情况,或者B1:B3有一些值,则需要修改或使用其他方法。 Or you could just use your loop, but I'd search for alternatives :)或者你可以只使用你的循环,但我会寻找替代品:)

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

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