excel - 如何遍历工作簿VBA中的所有工作表
问题描述
已编辑。试图通过整个 excel 工作簿循环我当前的 VBA 代码,已尝试 For Each ws In Sheets ws.Activate 但不起作用,它不会循环整个工作簿,而仅适用于我所在的工作表。任何帮助表示赞赏!
Sub InsertRows()
Dim ws As Worksheet
Dim rng As Range
Dim FirstRange As Excel.Range
For Each ws In Sheets
ws.Activate
Set rng = ActiveSheet.Cells.Find(What:="*XXX*", MatchCase:=False, Lookat:=xlWhole)
Do While Not rng Is Nothing
If FirstRange Is Nothing Then
Set FirstRange = rng
Else
If rng.Address = FirstRange.Address Then
Exit Do
End If
End If
If WorksheetFunction.CountBlank(rng.Offset(1).EntireRow) <> Columns.Count Then
rng.Offset(1).EntireRow.Insert
rng.Offset(1).EntireRow.Insert
End If
Set rng = ActiveSheet.Cells.FindNext(After:=rng.Cells(1))
Loop
Next ws
End Sub
解决方案
插入多行
在工作簿的每个工作表的单元格中,尝试查找指定的字符串,并在每个“找到”的单元格下方插入指定数量的行。
Sub insertMultiRows()
Const NumRows As Long = 2
Const Criteria As String = "XXX"
Dim wb As Workbook
Set wb = ThisWorkbook ' The workbook containing this code.
Dim ws As Worksheet ' Current Worksheet
Dim cel As Range ' Current Found Cell in Current Worksheet
Dim FirstCellAddress As String ' First Cell Address in Current Worksheet
' Loop through all worksheets in workbook.
For Each ws In wb.Worksheets
' Try to define the First Cell containing Criteria.
Set cel = ws.Cells.Find(What:=Criteria, _
After:=ws.Cells(ws.Rows.Count, _
ws.Columns.Count), _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows)
' Check if Criteria was found.
If Not cel Is Nothing Then
' Define First Cell Address.
FirstCellAddress = cel.Address
' Insert rows and try to find next occurrences of Criteria.
Do
' Check if next row is not blank.
If WorksheetFunction.CountBlank(cel.Offset(1).EntireRow) _
<> Columns.Count Then
' Insert rows.
cel.Offset(1).Resize(NumRows).EntireRow.Insert
End If
' Try to find the next occurrence of Criteria. You don't want
' to find multiple instances in row: use last cell in row.
Set cel = ws.Cells.FindNext(After:=ws.Cells(cel.Row, _
ws.Columns.Count))
' Check if current cell address is different then First Cell Address
' (to avoid infinite loop).
Loop While cel.Address <> FirstCellAddress
End If
Next ws
End Sub
推荐阅读
- javascript - 如何设置缩小矩形的样式
- javascript - vuex 突变不会更新 DOM
- python-3.x - H2O:GLM MOJO 模型的重要性不可变?
- java - 是否可以使用 ok google (如 whatsapp)在您的应用中发送消息?
- junit - 多次运行一组@Order 排序的 JUnit5 测试
- swiftui - 为什么 SwiftUI 视图仅在视图的第二次呈现后才填充注入的对象
- python - 错误:没有找到 keras==2.3.1 的匹配分布
- node.js - 如何使用时刻 js 将日期转换为从现在开始的小时数
- python - 在数据框中查找最常见/常见的值
- css - 使图像填充 flexbox 中的容器