遍历工作簿,但排除一些工作表?

这个问题已经多次在networking上问过,但没有一个全面的macros观计划。 我在一些工作表上有数据,但是我需要在一些单独的“分析表”上更具体地分析这些数据。 我相信问题可能是与ThisWorkbook.Sheets("sh")函数,因为它发出一个subscript out of range错误。

下面是代码,回应你将使这个代码工作的任何变化!

 Sub Excludesheet() Dim sh As Worksheet Const excludeSheets As String = "1-Analysis,2-Analysis" 'Assigns a Worksheet Object to the sh variable For Each sh In ThisWorkbook.Worksheets If IsError(Application.Match(sh.Name, Split(excludeSheets, ","))) Then 'This is for analysis worksheets Range("$A$1").Value = "Analysis" Else: 'Data Sheets Columns("A:M").AutoFit LR = Cells(Rows.Count, "A").End(xlUp).Row For i = LR To 2 Step -1 If Cells(i, "E").Text = "N/A" Then Rows(i).EntireRow.Delete Next i LastR = Cells(Rows.Count, "A").End(xlUp).Row Dim strFormulas(1 To 3) As Variant With ThisWorkbook.Sheets("sh") strFormulas(1) = "=(E2-$E$2)" strFormulas(2) = "=(G2-$G$2)" strFormulas(3) = "=H2+I2" Range("H2:J2").Formula = strFormulas Range("H2:J" & LastR).FillDown End With End If Next End Sub 

为了进一步澄清我的意见,直接处理你的对象。
检查了这一点的各种方式,你将如何做到这一点 。

现在尝试你的重构代码:

 Sub Excludesheet() Dim sh As Worksheet 'Const excludeSheets As String = "1-Analysis,2-Analysis" Dim excludeSheets: excludeSheets = Array("1-Analysis", "2-Analysis") For Each sh In ThisWorkbook.Worksheets With sh 'you already have the sheet object, so work with it If Not IsError(Application.Match(.Name, excludeSheets, 0)) Then 'This is for analysis worksheets .Range("$A$1").Value = "Analysis" Else 'Data Sheets .Columns("A:M").AutoFit LR = .Cells(.Rows.Count, "A").End(xlUp).Row For i = LR To 2 Step -1 If .Cells(i, "E").Text = "N/A" Then .Rows(i).EntireRow.Delete Next i LastR = .Cells(.Rows.Count, "A").End(xlUp).Row Dim strFormulas(1 To 3) As Variant strFormulas(1) = "=(E2-$E$2)" strFormulas(2) = "=(G2-$G$2)" strFormulas(3) = "=H2+I2" .Range("H2:J2").Formula = strFormulas .Range("H2:J" & LastR).FillDown End If End With Next End Sub 

我将使用With ... End With块来定义所有单元格和范围引用的父级。

 Sub Excludesheet() Dim i As Long, lr As Long, sh As Worksheet Const excludeSheets As String = "1-Analysis,2-Analysis" For Each sh In ThisWorkbook.Worksheets 'Assigns a Worksheet Object to the sh variable With sh If CBool(InStr(1, excludeSheets, .Name, vbTextCompare)) Then 'This is for analysis worksheets .Range("$A$1").Value = "Analysis" Else 'Data Sheets .Columns("A:M").AutoFit lr = .Cells(Rows.Count, "A").End(xlUp).Row For i = lr To 2 Step -1 If .Cells(i, "E").Text = "N/A" Then Rows(i).EntireRow.Delete Next i lr = .Cells(Rows.Count, "A").End(xlUp).Row Dim strFormulas(1 To 3) As Variant strFormulas(1) = "=(E2-$E$2)" strFormulas(2) = "=(G2-$G$2)" strFormulas(3) = "=H2+I2" .Range("H2:J2").Formula = strFormulas .Range("H2:J" & lr).FillDown End If End With Next sh End Sub 

我也重复使用了一些variables,所以新的variables不必被声明,并改变了确定工作表名称类别的方法。 你现有的方法似乎倒退(例如, 如果没有find ),所以我倒过来的逻辑。 如果我的假设是错误的,你可以扭转我的逻辑与If NOT CBool(InStr(...