设定范围无效

时间:2018-05-07 11:39:16

标签: excel vba excel-vba

我在VBA中获得了部分代码:

o = Workbooks(repfile).Worksheets("Families").Range("B:B").Cells.SpecialCells(xlCellTypeConstants).Count
Set rng = Workbooks(repfile).Worksheets("Families").Range("F2", Cells(o, 6))
A = 0
For Each cell In rng
    If IsError(cell) Then
    A = A + 1
End If
Next

但是我收到错误

  

应用程序定义或对象定义的错误

但如果我更正它:

o = Workbooks(repfile).Worksheets("Families").Range("B:B").Cells.SpecialCells(xlCellTypeConstants).Count
Set rng = Range("F2", Cells(o, 6)) 'correction
A = 0
For Each cell In rng
    If IsError(cell) Then
    A = A + 1
End If
Next

我没有错误 - 但由于我无法选择正确的工作表,因此整体代码无法正常工作

1 个答案:

答案 0 :(得分:1)

您的Cells函数隐含地引用了ActiveWorksheet,请尝试明确地引用其他工作簿。

o = Workbooks(repfile).Worksheets("Families").Range("B:B").Cells.SpecialCells(xlCellTypeConstants).Count
Set rng = Workbooks(repfile).Worksheets("Families").Range("F2", Workbooks(repfile).Worksheets("Families").Cells(o, 6))
A = 0
For Each cell In rng
    If IsError(cell) Then
        A = A + 1
    End If
Next

或者,尝试使用Resize功能:

With Workbooks(repfile).Worksheets("Families")
    o = .Range("B:B").Cells.SpecialCells(xlCellTypeConstants).Count
    Set rng = .Range("F2").Resize(o)
End With
A = 0
For Each cell In rng
    If IsError(cell) Then
        A = A + 1
    End If
Next
相关问题