loops - 向 Excel 的 vba 代码添加循环

标签 loops excel vba

我对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

最佳答案

您可以尝试以下方法:

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")

关于loops - 向 Excel 的 vba 代码添加循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16238951/

相关文章:

c for循环break语句不起作用

excel - 将 Excel 工作表中的文本和图像作为邮件正文复制到 Outlook

excel - 如何发送 session 请求,其中一位收件人的忙碌状态不在办公室,而一位收件人显示为空闲

excel - 如何创建制表符分隔的 CSV?

vba - 有更多关于 WordBasic 的 FilePrintSetup 的文档吗?

Excel VBA - 1004 运行时错误、应用程序或对象定义错误

java - 递归和辅助方法在查找字符出现时有用吗?

python - 通过列表迭代函数

javascript - 背景颜色没有改变

excel - Power Pivot 表 - 循环遍历报表过滤器中的字段