此代码试图打印一个名为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
我收到错误方法'范围'对象' _Worksheet'失败
答案 0 :(得分:0)
在工作表中循环不会自动将父项赋予工作表中引用的单元格范围。
为每个工作表的范围引用sh
。
strValidationRange = sh.Range("B2").Validation.Formula1
Set rngValidation = sh.Range(strValidationRange)
或者,使用With ... End With statement。
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
请注意.Name
和.Range
,而不是sh.Name
和Range
。
答案 1 :(得分:0)
你需要放置“sh”。作为每次出现Range()的前缀。