【问题标题】:How to fill in blank cells in this column, when the cells have to be populated with different values from this same column?当必须使用同一列中的不同值填充单元格时,如何填写该列中的空白单元格?
【发布时间】:2021-12-08 03:57:19
【问题描述】:

我一直在思考我目前面临的一个问题。

I have a file that looks like this

我怎样才能(使用 VBA)使列 (B) 填充第一个值 (P),直到它达到下一个值 (R),然后继续填充它 (R),直到它达到下一个值,依此类推,直到 (C) 列中的值结束? (如自动填充)

(B) 列中的值可以是 (P) 或 (R),但每次都不相同。以及行数。

Should look like this (blank rows can be deleted)

我已经尝试了一些方法来让它发挥作用。 首先,我编写了这个代码:

Dim nb As Workbook

nb.Sheets(2).Select
Range("C2").Select
i = 2

Do Until IsEmpty(Range("C" & i))

   If InStr(1, Range("C" & i), "") Then
   nb.Sheets(2).Range("B" & i) = nb.Sheets(2).Range("B2")

End If

i = i + 1

Loop

正如预期的那样,它只填充了列的第一部分:

Like this:

然后我尝试在代码中添加更多内容:

nb.Sheets(2).Select
Range("C2").Select

    Selection.End(xlDown).Select
    Selection.End(xlDown).Select

i = ActiveCell

Dim inD As String

    ActiveCell.Offset(0, -1).Select
    
inD = ActiveCell

    ActiveCell.Offset(0, 1).Select

Do Until IsEmpty(Range("C" & i))

    If InStr(1, Range("C" & i), "") Then
    nb.Sheets(2).Range("B" & i) = inD

End If

i = i + 1

Loop

但也正如预期的那样,这不起作用。看来您无法使用 ActiveCell 将单元格位置分配给 i。现在我收到“运行时错误 1004:对象的方法范围 - '全局'失败”

我也尝试了使用录音的自动填充,但也没有用。

非常感谢您在此问题上的帮助!

【问题讨论】:

    标签: excel vba loops range


    【解决方案1】:

    试试那个代码。您将获得与 Dominique 的过程类似的输出,但它也会删除空白行。

    Sub test()
    
    Dim sht     As Worksheet: Set sht = ActiveSheet
    Dim LastRow As Long
    Dim myRng   As Range
    
    'Find last row with data in sheet
    LastRow = sht.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
    
    'Set Range to fill in with values
    Set myRng = sht.Range("B2", "B" & LastRow - 1)
      
        'Loop through every cell in range and paste value from previous cell
        For Each cell In myRng
            If Not cell = "" Then
                If cell.Offset(1, 0) = "" And cell.Offset(1, 1) <> "" Then
                    cell.Offset(1, 0).Value = cell.Value
                Else
                    GoTo nextIteration
                End If
            
            End If
        
    nextIteration:
        Next cell
    
        'delete empty rows
        For x = LastRow To 1 Step -1
            If WorksheetFunction.CountA(Rows(x)) = 0 Then
                sht.Rows(x).Delete
            End If
        Next
    
    End Sub
    

    【讨论】:

    • 感谢您的回复@tomi09pl!我将使用 Dominique 的方法来解决这个问题,但是,您的解决方案将来会对我有用。不敢相信我没有想到根据以前的单元格值填充下一个空单元格...
    【解决方案2】:

    您可以按照以下步骤操作:

    • 选择整个 B 列
    • Ctrl+G启动“Goto”菜单,选择“Special”。
    • 选择“空白”
    • 在编辑栏中用鼠标单击并输入=B2
    • Ctrl+ENTER

    如果您想在宏中使用它,只需记录它即可。

    【讨论】:

      猜你喜欢
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-15
      • 2014-04-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多