[英]Elegant way of deleting a (the row of the) cell that contains “xxx” in Excel VBA
[英]Excel vba Deleting a row if a cell contains a text throughout whole workbook
我想基於參考單元重命名工作簿中的所有工作表,並刪除整個工作簿中C列中包含“-”的行,但是我不知道如何將在該論壇上找到的代碼應用於一整個工作簿(而不僅僅是一個工作表)。 請幫忙!
Sub Master()
Call RemoveRows()
Call RenameSheet()
End Sub
Sub RemoveRows()
Dim r As Integer
For r = Sheet1.UsedRange.Rows.Count to 1 step -1
If Cells(r, "C") = "-" Then
Sheet1.Rows(r).EntireRow.Delete
End If
Next
End Sub
Sub RenameSheet()
Dim rs As Worksheet
For Each rs In Application.ActiveWorkbook.Sheets
rs.Name = rs.Range("C3")
Next rs
End Sub
只需遍歷工作簿中的所有工作表,如下所示:
For Each ws in Application.ActiveWorkbook.Sheets
RemoveRows(ws) 'for each worksheet in ActiveWorkbook, call RemoveRows to remove its rows
Next ws
---------------------------------------------
Sub RemoveRows(Worksheet ws)
Dim r As Integer
For r = ws.UsedRange.Rows.Count to 1 step -1
If Cells(r, "C") = "-" Then
ws.Rows(r).EntireRow.Delete
End If
Next
End Sub
像這樣:
Option Explicit
Sub Master()
Dim ws As Worksheet
For Each ws in ActiveWorkbook.Worksheets
RemoveRowsWithDash ws
RenameSheet ws
Next ws
End Sub
Sub RemoveRowsWithDash(ws As Worksheet)
Dim r As Long
For r = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row to 1 step -1
If ws.Cells(r, "C") = "-" Then
ws.Rows(r).EntireRow.Delete
End If
Next r
End Sub
Sub RenameSheet(ws As Worksheet)
ws.Name = ws.Range("C3").Value
End Sub
您可以嘗試:
Option Explicit
Sub Master()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
Call RenameSheet(ws)
Call RemoveRows(ws)
Next ws
End Sub
Sub RenameSheet(ws As Worksheet)
With ws
.Name = .Range("C3").Value
End With
End Sub
Sub RemoveRows(ws As Worksheet)
Dim Lastrow As Long, Position As Long, i As Long
With ws
Lastrow = .Cells(.Rows.Count, "C").End(xlUp).Row
For i = Lastrow To 1 Step -1
Position = InStr(1, .Cells(i, "C").Value, "-")
If Position > 0 Then
.Rows(i).EntireRow.Delete
End If
Next i
End With
End Sub
注意
我認為最好是:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.