【问题标题】:Add loop to vba code for excel将循环添加到 Excel 的 vba 代码
【发布时间】:2013-04-26 14:30:02
【问题描述】:

我对vba知之甚少,希望有人能帮助我。

我在下面有以下代码,它“用上面的值填充列中的空白单元格”并且工作正常。

我需要在非连续列上使用它。 有没有办法给它添加一个循环,让它在 [B D H I] 列上运行?

我已经尝试过解决这个问题,但没有得到任何结果

谢谢

Sub FillColBlanks()
'by Dave Peterson  2004-01-06
'fill blank cells in column with value above
'http://www.contextures.com/xlDataEntry02.html
Dim wks As Worksheet
Dim rng As Range 
Dim Lastrow As Long
Dim col As Long

Set wks = ActiveSheet
With wks
   'col = ActiveCell.Column
   'or
   col = .Range("G2").Column

   Set rng = .UsedRange  'try to reset the lastcell
   Lastrow = .Cells.SpecialCells(xlCellTypeLastCell).Row
   Set rng = Nothing
   On Error Resume Next
   Set rng = .Range(.Cells(2, col), .Cells(Lastrow, col)) _
                  .Cells.SpecialCells(xlCellTypeBlanks)
   On Error GoTo 0

   If rng Is Nothing Then
       MsgBox "No blanks found"
       Exit Sub
   Else
       rng.FormulaR1C1 = "=R[-1]C"
   End If

   'replace formulas with values
   With .Cells(1, col).EntireColumn
       .Value = .Value
   End With

End With

End Sub

【问题讨论】:

    标签: loops excel vba


    【解决方案1】:

    您可以尝试以下方法:

    Sub FillColBlanks(sColRange as string)
    
    'by Dave Peterson  2004-01-06
    'fill blank cells in column with value above
    'http://www.contextures.com/xlDataEntry02.html
    Dim wks As Worksheet
    Dim rng As Range 
    Dim Lastrow As Long
    Dim col As Long
    
    Set wks = ActiveSheet
    With wks
       'col = ActiveCell.Column
       'or
       col = .Range(sColRange).Column
    
       Set rng = .UsedRange  'try to reset the lastcell
       Lastrow = .Cells.SpecialCells(xlCellTypeLastCell).Row
       Set rng = Nothing
       On Error Resume Next
       Set rng = .Range(.Cells(2, col), .Cells(Lastrow, col)) _
                      .Cells.SpecialCells(xlCellTypeBlanks)
       On Error GoTo 0
    
       If rng Is Nothing Then
           MsgBox "No blanks found"
           Exit Sub
       Else
           rng.FormulaR1C1 = "=R[-1]C"
       End If
    
       'replace formulas with values
       With .Cells(1, col).EntireColumn
           .Value = .Value
       End With
    
    End With
    
    End Sub
    

    所以你像这样调用这个过程:

    Call FillColBlanks("B1")
    Call FillColBlanks("D1")
    Call FillColBlanks("H1")
    Call FillColBlanks("I1")
    

    【讨论】:

    • + 1 那么如果你隐藏除 B,D,H,I 之外的所有列,那么你可以将它们视为一个范围吗?这会阻止您一次又一次地致电FillColBlanks?只是一个想法......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多