Vba 方法超出范围错误

Vba 方法超出范围错误,vba,excel,excel-2013,Vba,Excel,Excel 2013,这段代码试图只打印一张名为NQLD print的工作表,然后在该工作表B2单元格中的数据验证列表中循环使用所有选项: Sub PrintAll() Dim strValidationRange As String Dim rngValidation As Range On Error GoTo errhandler Dim rngDepartment As Range Dim sh As Worksheet For Each sh In ActiveWorkbook.Workshe

这段代码试图只打印一张名为NQLD print的工作表,然后在该工作表B2单元格中的数据验证列表中循环使用所有选项:

Sub PrintAll()

Dim strValidationRange As String
Dim rngValidation As Range
 On Error GoTo errhandler
Dim rngDepartment As Range
Dim sh As Worksheet

    For Each sh In ActiveWorkbook.Worksheets
        If (sh.Name = "NQLD PRINT") Then

      ' Turn off screen updating
            Application.ScreenUpdating = False
          ' Identify the source list of the data validation
             strValidationRange = Range("B2").Validation.Formula1
           Set rngValidation = Range(strValidationRange)
            ' Set the value in the selection cell to each selection in turn
            ' and print the results.

            For Each rngDepartment In rngValidation.Cells
            Range("B2").Value = rngDepartment.Value
            ActiveSheet.PrintOut

            Next

            Application.ScreenUpdating = True

   Exit Sub

errhandler: MsgBox Err.Description

End If

 Next

End Sub  

我获取对象“\u工作表”的错误方法“Range”失败。

在工作表中循环不会自动将父级授予工作表中引用的单元格范围

参考每个工作表范围的
sh

strValidationRange = sh.Range("B2").Validation.Formula1
Set rngValidation = sh.Range(strValidationRange)
或者,使用一个

请注意
.Name
.Range
而不是
sh.Name
Range

您需要将“sh.”作为Range()每次出现的前缀

For Each sh In ActiveWorkbook.Worksheets
    With sh
        If (.Name = "NQLD PRINT") Then
            ' Turn off screen updating
            Application.ScreenUpdating = False
            ' Identify the source list of the data validation
             strValidationRange = .Range("B2").Validation.Formula1
             Set rngValidation = .Range(strValidationRange)

             ' more stuff here
         End If
    Next sh