循环遍历单元格范围与工作表

时间:2015-02-18 15:03:45

标签: vba excel-vba excel

我有一张包含这么多张的工作簿。我有一张工作表中某处写的工作表名称列表。我需要编写一个函数来保护那些不在此列表中的工作表。

我想我被困在一行代码中。你能帮帮我吗?

Public Function Test()
On Error GoTo Test_Err

Dim wks, xSheet As Worksheet
Dim myRange As Range
Dim Cell As Range

Set wks = Worksheets("HideTabs")

With wks
Set myRange = .Range(.Cells(1, "D"), .Cells(.Rows.Count, "D").End(xlUp))
End With

For Each Cell In myRange
For Each xSheet In ActiveWorkbook.Worksheets

If xSheet.Name = Cell.Value Then
' Do Something
Exit For
Else
' Do Something else
End If

Next xSheet
Next Cell

Exit Function
Test_Err:
      MsgBox "The Error Happened on (Test Function) Line : " & Erl & vbNewLine & _
           "Error Message : " & Err.Description & vbNewLine & _
           "Error Number : " & Err.Number & vbNewLine & vbNewLine & _
           sMsg, vbCritical, sTitle

End Function

1 个答案:

答案 0 :(得分:0)

我成功地编写了一个函数来遍历所有工作簿表并将其与单元格范围内的已定义列表进行比较,然后执行一些操作。

Public Function Test()

Dim wks, xlWSH As Worksheet
Dim myRange, Cell As Range
Dim ProtectIt As Boolean

'Refer to sheet name where you save your sheet names list
Set wks = Worksheets("SheetName")
With wks
'Refer to first cell where your sheet names list starts. Here is "A1"
Set myRange = .Range(.Cells(1, "A"), .Cells(.Rows.Count, "A").End(xlUp))
End With

For Each xlWSH In ActiveWorkbook.Worksheets

For Each Cell In myRange
'If sheet name is in your list then set DoIt to False
If xlWSH.Name = Cell.Value Then
DoIt = False
Exit For
Else
DoIt = True
End If
Next Cell

If DoIt = True Then
With xlWSH
'Do Some Actions With Sheet
End With
End If

Next xlWSH

End Function