首页 > 解决方案 > 在单列中填充范围内的单元格,但仅填充下一个空白单元格

问题描述

我似乎找不到我要找的东西,所以我在这里。

情况:我们有一个供多个用户使用的电子表格。他们必须在某些单元格中填写员工姓名,但必须与我们系统中的输入完全相同。为了尽可能多地消除人为错误,我们制作了一个简单的按钮,他们可以在输入姓氏后按下,Vlookup 为我们提供了正确的格式。

问题:一列 (B10:B19) 中大约有 10 个单元格,这些单元格是名称所在的位置。vlookup 输出位于单元格 G4 中。因此,如果他们按下按钮,我们希望 G4 的内容进入 B10-B19 范围内的下一个可用单元格。我已经接近了,但它似乎跳过了一些行并错过了其他行。

这是我到目前为止所拥有的:

Sub SecondTestFunction()

    Dim cellRange As Range
    Dim nameInCell As Range
    Set cellRange = Range("B11:B20")
    
        'Loop through cells in range B11 thru B20
    For i = 1 To cellRange.Count
    
        'Set nameInCell to equal the index of column B
        Set nameInCell = cellRange(i)
        
        'If the cell in Column B is empty....
        If IsEmpty(nameInCell) Then
            'Paste the name from cell G4...
            nameInCell(i).Value = Range("G4")
                GoTo GoToHere
        Else
            MsgBox "Cell is NOT EMPTY"
            nameInCell(i).Interior.ColorIndex = 3 'Testing line to see which get affected
        
        End If

    Next i

GoToHere:

MsgBox "Done looping"

End Sub

任何帮助表示赞赏!

标签: excelvba

解决方案


你可以这样做:

Sub SecondTest()

    Dim c As Range, bFound As Boolean, ws As Worksheet
    Set ws = ActiveSheet 'always use an explicit sheet
   
    For Each c in ws.Range("B11:B20").Cells
        If Len(c.value) = 0 Then
            c.Value = ws.Range("G4").Value
            bFound = True
            Exit for
        End If
    Next c
    
    If not bFound Then Msgbox "No empty cell found!"

End Sub

推荐阅读