我正在使用列A中的excel表单,其中一个单元格包含工作簿名称(假设我的工作簿名称为abc,然后是#34; abc"位于A列的单元格中,可能在范围内&#34 ; A8或A9")。我想找出那一排&删除上面的所有行。我使用下面的代码
Option Explicit
Sub abc()
If Cells(8, 1).Value = ActiveWorkbook.Name Then
Range("A1:A7").Delete
Else
Range("A1:A8").Delete
End If
End Sub
如果有人可以帮助我解决问题,那请
答案 0 :(得分:0)
您可以找到工作簿名称并删除包含该名称的单元格上方的行:
Sub abc()
Dim SearchCol As Long, SearchRow As Long
Dim StrName As String
Dim FoundCell As Range
'get the workbook name after removing the extension
StrName = Left(ThisWorkbook.Name, (InStrRev(ThisWorkbook.Name, ".", -1, vbTextCompare) - 1))
'search for the workbook name
Set FoundCell = Cells.Find(What:=StrName, LookAt:=xlWhole)
If FoundCell Is Nothing Then
MsgBox "File name not found in Sheet" '---> if workbook name not found in the sheet
Else
Rows(1 & ":" & FoundCell.Row - 1).EntireRow.Delete '---> delete the rows if name found
End If
End Sub
的修改:
的 ------------------------------------------------------------------------ 强>
Option Explicit
Sub SearchWrkbookName()
Dim oSht As Worksheet
Dim lastRow As Long, i As Long
lastRow = 22
Dim strSearch As String
strSearch = Left(ActiveWorkbook.Name, (InStrRev(ActiveWorkbook.Name, ".", -1, vbTextCompare) - 1)) '---> to remove extension from worksheet name
Dim aCell As Range
Set oSht = Sheets(1)
Set aCell = oSht.Range("1:" & lastRow).Find(What:=strSearch, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
Rows("1:10").Select
End If
End Sub
已编辑的代码是您在评论中编写的代码的工作版本。