Вы можете использовать FIND
.Это найдет NO , но не Нет или nO (измените значение на MatchCase=False
, чтобы найти все случаи).
Public Sub SearchAndCopy()
Dim wb As Workbook
Dim ws As Worksheet
Dim ws1 As Worksheet
Dim last_row As Long
Dim rFound As Range
Dim sFirstAdd As String
Set wb = ThisWorkbook 'ActiveWorkbook
'Workbooks("SomeWorkbook.xlsx")
'Workbooks.Open("SomePath/SomeWorkbook.xlsx")
Set ws = wb.Worksheets("Sheet1")
Set ws1 = wb.Worksheets("Sheet2")
With ws.Columns("L")
Set rFound = .Find(What:="NO", _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchDirection:=xlNext, _
MatchCase:=True)
If Not rFound Is Nothing Then
sFirstAdd = rFound.Address
Do
'Find next empty row on destination sheet.
'Only really need to give worksheet reference when
'counting rows if you have 2003 & 2007+ files open - "ws.Rows.Count"
last_row = ws1.Cells(ws.Rows.Count, "A").End(xlUp).Row + 1
'Copy the figure from source to target sheet.
'You could also use Copy/Paste if you want the formatting as well.
ws1.Cells(last_row, 1) = ws.Cells(rFound.Row, 1)
'Look for the next matching value in column L.
Set rFound = .FindNext(rFound)
Loop While rFound.Address <> sFirstAdd
End If
End With
End Sub
Я добавил объяснение вашего кода ниже - главное, что неправильно с вашим кодом - ActiveCell.Range("A").Copy
.Нет диапазона A
, но есть A1
, A2
и т. Д.
Sub SearchMacro()
'You didn't declare these two which
'indicates you haven't got Option Explicit
'at the top of your module.
Dim RowCount As Long
Dim i As Long
Dim wb As Workbook
Dim ws As Worksheet
'I'll only comment that you set
'wb to be the ActiveWorkbook and you then
'activate the active workbook which is already active.....
Set wb = ActiveWorkbook
Set ws = Sheets("Sheet1")
wb.Activate
ws.Select
'Looks at the active sheet as you just activated it.
'Generally better to say "the cells in this named worksheet, even if it isn't active, or
'in the active book... just reference the damn thing."
'Something like "ws.cells(ws.cells.rows.count,"A").End(xlUp).Row"
'Note it references the correct worksheet each time.
RowCount = Cells(Cells.Rows.Count, "A").End(xlUp).Row
For i = 1 To RowCount
Range("L" & i).Select
If ActiveCell = "NO" Then
'Your code falls over here - you can't have range A.
'You can have range A1, which is the first cell in your referenced range.
'So ActiveCell.Range("A1") will return the ActiveCell - "L1" probably.
ActiveCell.Range("A1").Copy
'This will copy from column A using your method:
'ws.Cells(ActiveCell.Row, 1).Copy
'If you get the above line correct this will all work.
Sheets("Sheet2").Select
RowCount = Cells(Cells.Rows.Count, "A").End(xlUp).Row
Range("A" & RowCount + 1).Select
ActiveSheet.Paste
'You've already called it "ws" so just "ws.Select" will work.
Sheets("Sheet1").Select
End If
Next
End Sub