VBA调用子并使用当前子中的值

  • 本文关键字:调用 VBA excel vba
  • 更新时间 :
  • 英文 :


我对Excel宏还很陌生。我正在尝试构建一个时间表任务跟踪器,单击ActiveX控件按钮,按钮的标题写入列a,自定义输入列B和时间戳列C。

每个单独的按钮都会得到以下代码:

Private Sub CommandButton8_Click()
Dim Comments, ProjName As String
Comments = InputBox("Comment")
ProjName = CommandButton8.Caption
Cells(Rows.Count, "A").End(xlUp).Offset(1).Select
ActiveCell.Value = ProjName
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Comments
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Time
ActiveCell.NumberFormat = "h:mm AM/PM"
End Sub

它是有效的,但我知道复制所有这些8x是非常低效的,尤其是当唯一改变的是";ProjName=CommandButton#.Caption";。我认为它的大部分可能存在于我在命令按钮中调用的公共子中,我只是不知道如何让公共子从CommandButton子中提取ProjName值。任何关于如何使这一切更有效的建议都将不胜感激!

像这样:

Private Sub CommandButton8_Click()
AddRow CommandButton8.Caption
End Sub
Private Sub CommandButton9_Click()
AddRow CommandButton9.Caption
End Sub
'etc etc
'common code goes here...
Private Sub AddRow(ProjName As String)
Dim Comments
Comments = InputBox("Comment")
With Activesheet.Cells(Rows.Count, "A").End(xlUp).Offset(1).EntireRow
.Cells(1).Value = ProjName
.Cells(2).Value = Comments
.Cells(3).NumberFormat = "h:mm AM/PM"
.Cells(3).Value = Time
End With
End Sub

请注意,您不需要选择/激活单元格即可读取/写入它们。

最新更新