vba - 循环遍历具有多个 for 循环的工作表,并且内部的 If 函数不起作用
问题描述
该代码有效,但仅适用于当前工作表。我的目标是通过循环将功能代码应用于所有工作表。这段代码似乎没有循环。
Sub sbDelete_Rows_IF_Cell_Cntains_String_Text_Value()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
Dim lRow As Long
Dim iCntr As Long
lRow = 200
For iCntr = lRow To 1 Step -1
If Cells(iCntr, 3) = "PUT" Or Cells(iCntr, 3) = "CALL" Or Cells(iCntr, 3) = "PRN" Then
Rows(iCntr).Delete
End If
Next
Next ws
End Sub
如果我将 ws 名称添加到“单元格”,则会在“如果”行出现不匹配错误。这里出了什么问题?
Sub sbDelete_Rows_IF_Cell_Cntains_String_Text_Value()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
Dim lRow As Long
Dim iCntr As Long
lRow = 200
For iCntr = lRow To 1 Step -1
If ws.Cells(iCntr, 3) = "PUT" Or ws.Cells(iCntr, 3) = "CALL" Or ws.Cells(iCntr, 3) = "PRN" Then
Rows(iCntr).Delete
End If
Next
Next ws
End Sub
解决方案
始终声明父工作表(以及父工作簿,每当使用更多工作簿时)是一个很好的做法:
Sub sbDelete_Rows_IF_Cell_Cntains_String_Text_Value()
On Error GoTo sbDelete_Rows_IF_Cell_Cntains_String_Text_Value_Error
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
With ws
Dim lRow As Long
Dim iCntr As Long
lRow = 200
For iCntr = lRow To 1 Step -1
If .Cells(iCntr, 3) = "PUT" Or .Cells(iCntr, 3) = "CALL" Or .Cells(iCntr, 3) = "PRN" Then
.Rows(iCntr).Delete
End If
Next
End With
Next ws
On Error GoTo 0
Exit Sub
sbDelete_Rows_IF_Cell_Cntains_String_Text_Value_Error:
MsgBox "Error " & Err.Number & " on cell " & Cells(iCntr, 3).Address
End Sub
推荐阅读
- webpack - 如何使用 webpack 4 和 mini-css-extract-plugin 生成 css 文件?
- queue - 类不存在 octobercms
- excel - MATLAB:仅根据另一个变量绘制带有颜色条的 ponts
- vb.net - LINQ 在 Sum 中使用时如何返回 0 代替 NULL?
- sql-server - 不推荐使用 ISABOUT 用于 CONTAINSTABLE?
- opencv - recoverPose 的参数“triangulatedPoints”及其背后的数学
- javascript - 同一个React APP在不同浏览器渲染动画速度不同的原因是什么?
- python - 通过数据帧的子集更有效地使用 Python for 循环
- python - Shorter name for the class link in Sphinx
- sql-server - 从发布数据库 sys.sp_droparticle 和 sp_dropsubscription 中删除对象