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

时间:2016-03-25 22:47:56

标签: excel vba excel-vba

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

  • 只应在空白的单元格中插入数据。
  • 如果该范围内没有空单元格,则第二次单击该按钮将删除该名称。
  • 名称应在范围内从左向右插入。

我已经设法使用以下代码实现了一些,但由于在范围内随机选择了一个单元格(有时必须多次单击以显示名称),因此有点困难:< / p>

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

2 个答案:

答案 0 :(得分:1)

问题有点不清楚,所以答案是通用的:为了实现所描述的目标,你可以修改你的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

希望这可能会有所帮助。

答案 1 :(得分:1)

我不完全确定你想要实现的目标。据我了解,以下内容应该可以完成任务。

    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