我想使用VBA在Excel中循环遍历工作表的子集。我想在单个工作表中定义工作表列表,然后我想循环遍历该列表。下面我有代码来循环整本书,但我想要的只是循环我定义的工作表的子集。我设想的是定义一系列纸张然后循环到该范围。任何见解都将不胜感激。
Sub cyclethroughwbs()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Sheets
ws.Select
ws.Calculate
Next ws
End Sub
答案 0 :(得分:1)
说 Sheet1 包含要在 A 列中处理的工作表列表:
此代码将遍历它们:
Sub LoopOverListOfSheets()
Dim N As Long, i As Long
With Sheets("Sheet1")
N = .Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To N
Sheets(.Cells(i, "A").Value).Select
Sheets(.Cells(i, "A").Value).Calculate
Next i
End With
End Sub
答案 1 :(得分:0)
我提出了两种不同的技术,既处理可能的空白单元格,也处理不存在的工作表
第一个是“几乎所有的一体化”子
public static T Deserialize<T>(string xml){
XmlSerializer xs = new XmlSerializer(typeof(T));
string cleanXml = Regex.Replace(xml, @"<[a-zA-Z].[^(><.)]+/>",
new MatchEvaluator(RemoveText));
MemoryStream memoryStream = new MemoryStream((new UTF8Encoding()).GetBytes(cleanXml));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
return (T)xs.Deserialize(memoryStream);
}
static string RemoveText(Match m) { return "";}
第二种解决方案使用更多“包装”函数来保持代码清洁和可维护。它还使用Collection对象来处理所有未找到的工作表
Option Explicit
Sub LoopOverListOfSheets()
Dim shtNamesRng As Range, cell As Range
Dim sht As Worksheet
With ThisWorkbook.Worksheets("SheetWithNames")
Set shtNamesRng = .Range("A1", .Cells(.Rows.Count, "A").End(xlUp)).SpecialCells(xlCellTypeConstants, xlTextValues)
End With
For Each cell In shtNamesRng
Set sht = SetSheet(ThisWorkbook, cell.Value)
If Not sht Is Nothing Then
With sht
.Calculate
'... other code on "sht"
End With
End If
Next cell
End Sub
Function SetSheet(wb As Workbook, shtName As String) As Worksheet
On Error Resume Next
Set SetSheet = wb.Worksheets(shtName)
On Error GoTo 0
End Function