使用VBA将变量文本字符串(时间戳)插入单元格

时间:2018-05-17 15:57:58

标签: string vba excel-vba text copy

我正在尝试简化在电子表格中记录记录的过程。我想在单元格中插入时间戳(具有特定格式),然后继续键入注释。

这是我在VBA中的代码:

Sub timestamp()

Dim stringdate As String
Dim stringtime As String
Dim stamp As String




stringdate = Format(Now(), "mm/dd/yy")
stringtime = Format(Now(), "hh:mmA/P")
stamp = stringdate & " @" & stringtime & " KB- "


Selection.Value = stamp

'SendKeys "{F2}" /// not working

End Sub

这会以我想要的格式插入时间戳,但我有两个问题。 (1)我需要能够在插入文本后继续键入并且sendkeys不起作用。 (2)我还希望能够在以后导航回该单元格,并在下面添加更多笔记的新时间戳。

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

如果我了解您的问题,您希望在编辑单元格时运行宏。那是不可能的。所以我想提供一个解决方法。 把它放在你的图纸模块中:

Const MAGIC_CHARACTER = "¤"

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim stringdate As String
    Dim stringtime As String
    Dim stamp As String

    Application.EnableEvents = False

    stringdate = Format(Now(), "mm/dd/yy")
    stringtime = Format(Now(), "hh:mmA/P")
    stamp = stringdate & " @" & stringtime & " KB- "

    Target.Value = Replace(Target.Value, MAGIC_CHARACTER, stamp)

    Application.EnableEvents = True
End Sub

当您需要时间戳时,请输入魔术角色,这必须是您永远不会使用的东西,但您仍然可以轻松访问键盘。在我的情况下,我选择“¤”,但你可能使用不同的键盘布局,所以选择适合你的东西。离开单元格后,魔术字符将替换为时间戳。

答案 1 :(得分:0)

你已经有了一个答案,这是一个有点不同的方法:

您必须将其粘贴到您将键入注释的工作表模块中。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim tAddress As Variant
    tAddress = Split(Target.Address, "$")
    If tAddress(1) = "B" And tAddress(2) > 1 Then
        If Cells(tAddress(2), 1).Value = "" Then Cells(tAddress(2), 1) = Format(Now(), "mm/dd/yy: h:mm:ss AM/PM")
        Application.SendKeys "{F2}", False
    End If
End Sub

无论何时选择B列中的任何单元格(B1除外),如果A列旁边的单元格为空白,它将为其添加时间戳并激活单元格,以便您可以在其上键入。无论何时移动到B列中的下一个单元格,它都会再次执行。如果您回到已经输入的单元格,它将不会更改时间戳,但可以轻松编辑它。

答案 2 :(得分:0)

感谢您的反馈。我决定使用以下代码:

Sub MyTimestamp()
'
' MyTimestamp Macro
' Insert KB Date/Time stamp into cell
'
' Keyboard Shortcut: Ctrl+Shift+D



Dim stringdate As String
Dim stringtime As String
Dim stamp As String
Dim current_value As String

stringdate = Format(Now(), "mm/dd/yy")
stringtime = Format(Now(), "hh:mmA/P")
stamp = stringdate & " @" & stringtime & " KB- "

current_value = Selection.Value

If current_value = "" Then
Selection.Value = current_value & stamp
Else: Selection.Value = current_value & Chr(10) & stamp
End If


Application.Wait (Now() + TimeValue("00:00:01"))
SendKeys "{f2}", True



End Sub
相关问题