我是Excel和VBA的新手,所以请耐心等待。
我有一个宏:
但后来我需要它:
我必须遵循以下代码:
Sub SearchForString()
Dim LSearchRow As Integer
Dim LCopyToRow As Integer
Dim LSearchValue As String
Dim shName As String
On Error GoTo Err_Execute
Application.ScreenUpdating = False
LSearchValue = Cells(1, 7)
shName = LSearchValue
LSearchRow = 21
'Start copying data to row 2 in Sheet2 (row counter variable)
LCopyToRow = Worksheets(shName).Cells(Rows.Count, "A").End(xlUp).Row + 1
If LCopyToRow < 2 Then LCopyToRow = 2
While Len(Range("A" & CStr(LSearchRow)).Value) > 0
'If value in column E = LSearchValue, copy entire row to Sheet2
If Range("E" & CStr(LSearchRow)).Value = LSearchValue Then
'Select row in Sheet1 to copy
Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Select
Selection.Copy
'Paste row into Sheet2 in next row
Sheets(shName).Select
Rows(CStr(LCopyToRow) & ":" & CStr(LCopyToRow)).Select
ActiveSheet.Paste
LCopyToRow = LCopyToRow + 1
Sheets("Sheet1").Select
End If
LSearchRow = LSearchRow + 1
Wend
Application.CutCopyMode = True
Range("A1").Select
MsgBox "All matching data has been copied."
Exit Sub
Err_Execute:
MsgBox "An Error Occured"
End Sub
有人能帮助我吗?任何帮助将不胜感激
答案 0 :(得分:0)
尝试使用以下代码
注意:假设搜索条件列中没有空白单元格,即列“G”。
Sub SearchForString()
Dim LSearchRow As Integer
Dim LCopyToRow As Integer
Dim LSearchValue As String
Dim shName As String
On Error GoTo Err_Execute
Application.ScreenUpdating = False
'let's find the last cell in G column
Dim lastRow As Long
Dim i as Integer
lastRow = ActiveSheet.Range("G1").End(xlDown).Row
for i = 1 to lastRow
LSearchValue = Cells(i, 7)
shName = LSearchValue
LSearchRow = 21
'Start copying data to row 2 in Sheet2 (row counter variable)
LCopyToRow = Worksheets(shName).Cells(Rows.Count, "A").End(xlUp).Row + 1
If LCopyToRow < 2 Then LCopyToRow = 2
While Len(Range("A" & CStr(LSearchRow)).Value) > 0
'If value in column E = LSearchValue, copy entire row to Sheet2
If Range("E" & CStr(LSearchRow)).Value = LSearchValue Then
'Select row in Sheet1 to copy
Rows(CStr(LSearchRow) & ":" & CStr(LSearchRow)).Select
Selection.Copy
'Paste row into Sheet2 in next row
Sheets(shName).Select
Rows(CStr(LCopyToRow) & ":" & CStr(LCopyToRow)).Select
ActiveSheet.Paste
LCopyToRow = LCopyToRow + 1
Sheets("Sheet1").Select
End If
LSearchRow = LSearchRow + 1
Wend
Application.CutCopyMode = True
Range("A1").Select
Next
MsgBox "All matching data has been copied."
Exit Sub