VBA:从处理中跳过空白单元格(其中包含公式)

时间:2016-12-28 19:39:17

标签: excel vba


我有一个vba代码,它复制一个文件多次,并在表D列中的名字列表之后重命名输出" Linkuire"。
D列充满了连接公式,这些公式将数据引入单元格直到D1000 当连接公式返回"" (没有什么)我希望代码忽略该单元格。

 ' the range of cells that contain the rename list
With ActiveWorkbook.Sheets("Linkuire")  
 Set rRenameList = .Range("D2", .Cells(.Rows.Count, "D").End(xlUp))
End With 

现在它只考虑了所有D2到D1000的细胞,即使有些是=""

如何让代码忽略连接返回的所有单元格"" ?(我对将某个工作表转换为pdf的vba代码有同样的问题 - 数据来自连接公式。即使连接返回""并且为空白,它也会转换所有单元格)

谢谢..

2 个答案:

答案 0 :(得分:1)

编辑,因为 SpecialCells()方法不起作用

您可以使用以下两种方法并避免循环:

  • AutoFilter()SpecialCells()方法:

    With ActiveWorkbook.Sheets("Linkuire")
        With .Range("D1", .Cells(.Rows.count, "D").End(xlUp))
            .AutoFilter Field:=1, Criteria1:="<>" '<--| filter out blanks
            If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then Set rRenameList = .Resize(.Rows.count - 1).Offset(1).SpecialCells(xlCellTypeVisible)
        End With
        .AutoFilterMode = False
    End With
    
  • 公式和SpecialCells()方法

    With ActiveWorkbook.Sheets("Linkuire")
        With .Range("D2", .Cells(.Rows.count, "D").End(xlUp))
            .Offset(, 1).FormulaR1C1 = "=IF(RC[-1]="""", 1,"""")"
            Set rRenameList = .Offset(, 1).SpecialCells(xlCellTypeFormulas, xlNumbers).Offset(, -1)
            .Offset(, 1).ClearContents
        End With
    End With
    

    在这种方法中,你在“帮助者”栏中写了一个公式,我选择了与右边相邻的列。它可以调整到任何其他偏移量

答案 1 :(得分:0)

这应该有效。它将遍历您的范围,并且仅在长度大于或等于1时将单元格地址添加到rRenameList

Sub Test()
' Adapted from http://stackoverflow.com/a/8320884/4650297

  Dim rng1 As Range, rRenameList As Range, cel As Range
  With ActiveWorkbook.Sheets("Linkuire")
    Set rng1 = .Range("D2", .Cells(.Rows.Count, "D").End(xlUp))
  End With

  For Each cel In rng1
    If Len(cel) >= 1 Then
        If Not rRenameList Is Nothing Then
            Set rRenameList = Union(rRenameList, cel)
        Else
        ' the first valid cell becomes rng2
            Set rRenameList = cel
        End If
    End If
  Next cel

Debug.Print rRenameList.Address
End Sub