在单元格范围内使用button插入单个值

我正在尝试使用VBA将名称插入一个小型单元格区域(水平方向6个单元格),并考虑到以下条件:

  • 数据只能插入空白的单元格中。
  • 如果在该范围内没有空单元格,则再次单击该button应删除该名称。
  • 名称应该在范围内从左到右插入。

我已经设法使用下面的代码来实现其中的一部分,但是由于在该范围内随机select一个单元格(有时必须多次点击以显示该名称),这有点困难:

Sub button_onclick() Dim rCells As Range Set rCells = Range("N3:S3") Dim rRandom As Long rRandom = Int(Rnd * rCells.Cells.Count) + 1 With rCells.Cells(rRandom) If IsEmpty(rCells.Cells(rRandom)) Then .Value = "Kent Allard" End If End With End Sub 

这个问题有点不清楚,所以答案是一般的:为了达到上述目标,你可以修改你的Sub,如下所示:

 Sub button_onclick() Dim rCells As Range Set rCells = Range("N3:S3") Dim rRandom As Long rRandom = Int(Rnd * rCells.Cells.Count) + 1 With rCells.Cells(rRandom) If IsEmpty(rCells.Cells(rRandom)) Then .Value = "Kent Allard" Else .Value = "" End If End With End Sub 

与您的修改要求相关(单元格按顺序而不是随机填充,最后一个要清除的单元格如果不为空),请参阅以下代码片段:

 Sub button_onclick() Dim rCells As Range Dim I As Integer, max As Integer Set rCells = Range("N3:S3") max = Range("S3").Column - Range("N3").Column + 1 For I = 1 To max With rCells.Cells(I) If IsEmpty(rCells.Cells(I)) Then .Value = "Kent Allard" Exit For Else If I = max Then .Value = "" End If End With Next I End Sub 

希望这可能有帮助。

我不完全确定你想要达到什么目的。 据我了解,以下任务应该可以完成。

  Sub CommandButton1_Click() Dim rCells As Range Dim rRandom As Long Dim intFilledCells As Integer Set rCells = Range("N3:S3") rRandom = Int(Rnd * 21) + 1 ' You could achieve the placement of a random name by making a list ' of the 21 names (here it is supposed they are written in the cells A1:A21 intFilledCells = WorksheetFunction.CountA(rCells) If intFilledCells <= 5 Then Range("N3").Offset(0, intFilledCells).Value = Range("A" & rRandom).Value Else Range("N3").Offset(0, intFilledCells - 1).Value = "" End If End Sub