从所选单元格(或范围)中select第一个空单元格,然后添加值(date),然后添加偏移量和inputext

我一直在寻找好的例子,但找不到我需要的东西。
这里是上下文:代码是销售跟踪工作表与大约50个供应商(他们每个人都可以增加价值,他们中的大多数不知道任何关于Excel)。

我想select第一个空单元格(首先他们可以input一个值是B5,而不是更高,因为表单的顶部包含一些指令)。 事实上,从这个单元格(date值在列B中,并在行5开始)第二个date值是在B6

Add the Date (date or now) as activecell.value Then 2 cells to the right activecell.offset(0,2) And insert the value of the textbox (their ID). 

现在,我可以添加date和文本框ID。
这里我到目前为止:

 Sub CommandButton1_click() Dim Input_ID As String, Date_in As String Date_in = Format(Now, "DD-MMM") ActiveCell.Value = Date_in Input_ID = InputBox("SVP entré votre ID ", "Data Entry Form") ActiveCell.Offset(0, 2) = Input_ID End Sub 

但是是否可以使该命令/button仅用于列“B?” 因为我不是他们添加date和他们的ID到另一个列。
PS:我或多或less地从VBA开始,我从各地学习,所以如果你可以在你的代码中添加一些解释,我很感激。 谢谢

编辑1:发表评论

 Sub Date_insert_click() Dim Input_ID As String, Date_in As String Dim ws As Worksheet Set ws = ActiveSheet 'change to your actual worksheet 'Dim Date_in As Date Date_in = Format(Now, "DD-MMM") With ws.Range("B" & ws.Rows.Count).End(xlUp) If .Row >= 4 Then .Offset(1, 0).Value = Date_in Else Exit Sub Input_ID = InputBox("SVP entré votre ID ", "Data Entry Form") If Input_ID <> "" Then .Offset(1, 1).Value = Input_ID Else .Offset(1, 0).Value = "" End With End Sub 

但是我发现了一个弱点。 如果我select一个像K378一样的小区,
我仍然可以添加值(date_In或input框的值),但不能看到它,因为单元格不活动。

尝试这个评论:

 Sub CommandButton1_click() Dim Input_ID As String, Date_in As String Dim ws As Worksheet Set ws = Thisworkbook.Sheets("Sheet1") 'change to your actual worksheet Date_in = Format(Now, "DD-MMM") With ws.Range("B" & ws.Rows.Count).End(xlUp) If .Row >= 4 Then .Offset(1, 0).Value = Date_in Else Exit Sub Input_ID = InputBox("SVP entré votre ID ", "Data Entry Form") If Input_ID <> "" Then .Offset(1, 2).Value = Input_ID Else .Offset(1, 0).Value = "" End With End Sub 

编辑1:按要求解释

问:为什么要将Worksheet对象传递给一个variables?
答: 这里是对这个问题的一些解释。 它也使你的代码更易读,易于debugging。

解释代码:

 'This line simply finds the last cell in Column B With ws.Range("B" & ws.Rows.Count).End(xlUp) 'other code here End With 

为什么使用? 我曾经使用过,因为所有的编码重点在Column B和其他数据input也参考它。
您也可以在上面提供的链接中看到使用它的优点的解释。

 With ws.Range("B" & ws.Rows.Count).End(xlUp) 'Since we used With, you can directly access the Range properties 'The following line uses the Row and Offset property 'Row returns the row number of the range you're workning on 'Offset literally offets the range you are currently working on If .Row >= 4 Then .Offset(1, 0).Value = Date_in Else Exit Sub 'This next line is already known to you, no need to explain Input_ID = InputBox("SVP entré votre ID ", "Data Entry Form") 'Next line checks if Input_ID is supplied 'If yes, we use offset to get to the 2nd column from the current range 'If no, we delete the Date_In value If Input_ID <> "" Then .Offset(1, 2).Value = Input_ID Else .Offset(1, 0).Value = "" End With 

我希望我解释得够。
但是,如果你还需要更多的解释,只是注释掉。
如果你遇到困难,只是在另一个问题上。