这个问题已在网上多次被问到,但宏内没有全面的程序。我有一些工作表上的数据,但我需要在一些单独的“分析表”上更具体地分析这些数据。我认为问题可能与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
答案 0 :(得分:1)
为了进一步澄清我的评论,请直接处理您的对象 Check this out for various ways on how you'll do that
现在尝试这个重构的代码:
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
答案 1 :(得分:1)
我会使用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
我还重用了一些变量,因此无需声明新变量,并更改了确定工作表名称类别的方法。你现有的方法对我来说似乎是倒退的(例如,如果没有找到),所以我颠倒了逻辑。如果我的假设是错误的,你可以用If NOT CBool(InStr(...
来反转我的逻辑。