带有“粘贴date”function的命令button到其左下angular的单元格

我想创build一个Commandbutton的function,将date粘贴到其左侧的单元格 – 我需要将来复制下面的这个button。

我在尝试:

 Private Sub CommandButton2_Click() Dim Str As String Str = Date Range(TopLeftCell).Value = Str End Sub 

我会build议使用Form Control而不是ActiveX control ,原因很简单。 当您复制button时,到macros的链接保持不变。 ,这也是你的要求之一。

这是您可以用于CommandButton(窗体控件)的代码

 Sub Button1_Click() Dim cellAddr As String Dim aCol As Long '~~> Get the address of the cell cellAddr = ActiveSheet.Shapes(Application.Caller).TopLeftCell.Address '~~> Also get the column number aCol = ActiveSheet.Shapes(Application.Caller).TopLeftCell.Column '~~> This is required if the button is in column 1 If aCol <> 1 Then _ ActiveSheet.Range(cellAddr).Offset(, -1).Value = Date End Sub 

指向一个特定的范围做这样的事情:

 Private Sub CommandButton1_Click() Dim Str As String Str = Date Range("C5").Value = Str End Sub 

或者使用命名的范围,即给range C5的名称“TopLeftCell”

在这里输入图像描述

…那么你可以使用以下内容:

 Private Sub CommandButton1_Click() Dim Str As String Str = Date Range("TopLeftCell").Value = Str End Sub 

像这样的东西:

 Private Sub CommandButton2_Click() Dim r As Long, c As Long, i As Long Dim str As String r = Rows.Count c = Columns.Count str = Date For i = 1 To r If Cells(i, 1).Top > CommandButton2.Top Then Exit For End If Next r = i - 1 ' you have to calibrate, what fits better r = i or r = i - 1 or r = i - 2 .... For i = 1 To c If Cells(1, i).Left > CommandButton2.Left Then Exit For End If Next c = i - 2 ' you have to calibrate, what fits better c = i or c = i - 1 or c = i - 2 .... Cells(r, c) = str End Sub 

这应该工作,但这取决于你放置button的位置。 看看r = i - 1c = i - 2