早上好, 在列中搜索特定字符串时,出现91运行错误。
我试图修改逻辑-将结果复制到新工作表中,然后进行删除-参见第二段代码。
然后,我发现发生这种情况是因为vba找不到文本,所以我问了一个使用所请求语言运行此报告的人来更改“ ??????? ATLAS ????-???”。 ”以数据源语言编写它的方式。但这没有帮助。
Columns("A:A").Select
Selection.Find("??????? ATLAS ????-???", LookIn:=xlValues).Select
Range(ActiveCell.Address & ":" & Cells(Cells(Rows.Count, "A").End(xlUp).Row, ActiveCell.Column + 4).Address).Select
Selection.Copy
'Pasting the Ylan-Yde data to the new sheet
Sheets("interim").Select
Range("A1").Select
ActiveSheet.Paste
'Copying the Ylan-Yde data to a new sheet
Cells.Select
Selection.Copy
Sheets("interim").Select
Cells.Select
ActiveSheet.Paste
Columns("A:A").Select
Selection.Find("??????? ATLAS ????-???", LookIn:=xlValues).Select
Range("A1:A" & ActiveCell.Row - 1).EntireRow.Delete```
If I stick to the 2nd version, the code is supposed to find the a certain string in a column (it is present only once) and delete all rows before the row with the found string.
答案 0 :(得分:1)
您应该避免使用.Select
,因为如果用户与excel进行交互,则一切都会出错。相反,您需要为工作簿和工作表声明变量。
此方法假设您的单词仅出现一次,并且其Length始终为22,因此该列上显示的其他ATLAS的长度也不相同。考虑到这一点,它应该起作用:
Option Explicit
Sub Test()
Dim arr As Variant, LastRow As Long, ws As Worksheet, wsInterim As Worksheet, i As Long, StartRow As Long, NowDelete As Boolean
With ThisWorkbook
Set ws = .Sheets("NameWhereAtlasIs")
Set wsInterim = .Sheets("Interim")
End With
With ws
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
arr = .Range("A1:A" & LastRow).Value 'store the column A inside an array
End With
NowDelete = False
For i = 1 To UBound(arr) 'find the ATLAS with the exact length match.
If arr(i, 1) Like "*ATLAS*" And Len(arr(i, 1)) = 22 Then
StartRow = i
NowDelete = True
arr(i, 1) = vbNullString 'if you intend to delete this row too, the one with the ATLAS
End If
If NowDelete Then arr(i, 1) = vbNullString 'from the moment you find your match all the rows will be emptied on column A
Next i
ws.Range("A" & StartRow & ":A" & LastRow).Copy wsInterim.Range("A1")
ws.Range("A1:A" & LastRow).Value = arr 'this would paste the array back with the empty cells you cleared before
End Sub