按下命令按钮可在所需范围内循环

我正在尝试将代码写入到每次按下命令按钮的位置,当前时间被放入范围内的第一个单元格中。然后,在下一个按钮上单击,范围中的下一个单元格将填充当前时间,依此类推。我无法弄清楚如何在所需范围内循环,并在每次按下按钮时在该单元格上放置一个时间值。

我有一个基本的double For循环,该循环遍历所需的整个范围,并立即用当前时间填充所有单元格。我只希望每次单击按钮时一次填充一个当前时间的单元格,而我无法弄清楚自己的一生。

到目前为止的

代码:

Private Sub CommandButton1_Click()

Dim i As Integer,j As Integer

For i = 6 To 115
    For j = 3 To 5
        Cells(i,j).Value = Time
    Next j
Next i


End Sub
liyqiy 回答:按下命令按钮可在所需范围内循环

这应该可以解决问题:

Option Explicit

Private Sub CommandButton1_Click()

  Dim i As Integer,j As Integer
  Dim emptyCellFound As Boolean
  Dim c As Range

  emptyCellFound = False 'not really needed. just for clarity

  For i = 6 To 115
    For j = 3 To 5
      Set c = Cells(i,j)
      If c.Value = "" And Not emptyCellFound Then
        c.Value = Time
        emptyCellFound = True
      End If
    Next j
  Next i

End Sub
,

我这样理解

Private Sub CommandButton1_Click()

    Dim rg As Range
    Set rg = Range("C6:E115")

    Dim sngCell As Range
    For Each sngCell In rg
        If Len(sngCell.Value) = 0 Then
            sngCell.Value = Time
            Exit For
        End If
    Next

End Sub

更新

此解决方案应该更快,但我认为它不会引起注意。

  Private Sub CommandButton1_Click()

    Dim rg As Range
    Set rg = Union(Range("C5"),Range("C6:E115"))

    Dim nextCell As Range
    Set nextCell = rg.Find("")
    If Not nextCell Is Nothing And nextCell.Address <> "$C$5" Then
        nextCell.Value = Time
    End If

End Sub
,

如果在第114行下方的任何单元格中应用了任何值,则此方法有效

Private Sub CommandButton1_Click()
    On Error Resume Next
    [C6:E115].SpecialCells(xlCellTypeBlanks).Cells(1).Value = Time
    On Error GoTo 0
End Sub

..在第114行以下没有值的情况下

Private Sub CommandButton1_Click()
    On Error GoTo weird
    [C6:E115].SpecialCells(xlCellTypeBlanks).Cells(1).Value = Time
    Exit Sub
weird:
    If [C115].End(xlUp).Row > 6 Then [C115].End(xlUp).Offset(1).Value = Time
    On Error GoTo 0
End Sub
本文链接:https://www.f2er.com/3154429.html

大家都在问