循环范围类型不匹配

时间:2016-11-08 19:09:51

标签: excel-vba vba excel

我正在尝试重建我们每天使用的工作表,并在此过程中使其更快。我现在一直在使用范围并尝试合并这些但尝试使用UsedRange来获取范围的最后一行而不是找到它时遇到问题。

我的代码:

Sub RebuildAllFormat()

Dim SheetRNG As Range, RowDelete As Range, SOSheet As Worksheet

Set SOSheet = ThisWorkbook.Worksheets(Sheet1.Name)

Set SheetRNG = SOSheet.UsedRange.Columns(1)   

For Each cell In SheetRNG
    If cell.Value = "" Then
        Cells(cell.Row, "P").Cut Cells(cell.Row - 1, "P")
                If Not RowDelete Is Nothing Then
                    Set RowDelete = Union(RowDelete, cell)
                Else
                    Set RowDelete = cell
                End If
    End If
Next cell

RowDelete.EntireRow.Delete

End Sub

上面的代码在If cell.Value = "" Then上给出了“类型不匹配”错误,并且看起来For循环不再遍历每个单元格,即使我从Debug.Print SheetRNG.Address获得了$ A的预期值$ 1:$ A $ 1736年

如果我用

替换Set SheetRNG = SOSheet.UsedRange.Columns(1)
lastrow = SOSheet.Cells(Rows.Count, "B").End(xlUp).Row

Set SheetRNG = SOSheet.Range(SOSheet.Range("A1"), SOSheet.Cells(lastrow, "A"))

然后循环按预期工作,我能够检查值。使用上述内容后运行Debug.Print SheetRNG.Address也会返回$ A $ 1:$ A $ 1736。

我是否遗漏了UsedRange代码中的内容,或者无法以这种方式使用它?

2 个答案:

答案 0 :(得分:1)

正如其他人所说,并且您自己确定了问题,问题是For Each cell In SheetRNG将整个版本返回到cell

使用For Each cell In SheetRNG.Cells分别获取每个单元格。

代码中还有其他问题。请参阅以下有关推荐的评论

Sub RebuildAllFormat()
    Dim SheetRNG As Range, RowDelete As Range, SOSheet As Worksheet
    Dim cell as Range '<~~ Dim all variables

    Set SOSheet = Sheet1 '<~~ Sheet1 is already a Worksheet reference

    Set SheetRNG = SOSheet.UsedRange.Columns(1) '<~~ May overstate the required range, but will work OK 

    For Each cell In SheetRNG.Cells
        If cell.Value = "" Then
            '~~ Qualify the Sheet reference, otherwise it refers to the active sheet
            With SOSheet 
                .Cells(cell.Row - 1, "P") = .Cells(cell.Row, "P") '<~~ faster than Cut/Paste
                If Not RowDelete Is Nothing Then
                    Set RowDelete = Union(RowDelete, cell)
                Else
                    Set RowDelete = cell
                End If
            End With
        End If
    Next cell

    '~~ Avoid error if no blanks found
    If Not RowDelete Is Nothing Then
        RowDelete.EntireRow.Delete
    End If
End Sub

答案 1 :(得分:0)

.Columns(1)语句与您使用它的方式不同。例如:

Set SheetRNG = Range("A1:B19").Columns(1)

不一样:

Set SheetRNG = Range("A1:A19")

您可以.Resize() .UsedRange

   Set SheetRNG = SOSheet.UsedRange.Resize(SOSheet.UsedRange.Rows.Count, 1)