【发布时间】:2019-10-24 00:53:12
【问题描述】:
Sheet(LIST2) 有 8 列。Sheet(LIST2) 的 A 列包含 ID 号。相同的 ID 号在 A 列的许多行中重复多次。B 列到 H 列包含其他数据。 在 sheet(Sheet1) A1 中,我们键入一个 ID 号,该 ID 号在 Sheets(LIST2) A 列中找到匹配项,并将每个数学行从 A 复制到 H
我找到了复制整个行的代码,但我想要的只是 A 到 H 行
Sub SearchForString()
Dim LCopyToRow As Integer
On Error GoTo Err_Execute
'Start copying data to row 2 in Sheet2 (row counter variable)
LCopyToRow = 3
Dim sheetTarget As String: sheetTarget = "sheet1"
Dim sheetToSearch As String: sheetToSearch = "LIST2"
Dim targetValue As String: targetValue = Sheets(sheetTarget).Range("A1").Value 'Value in sheet2!A1 to be searched in sheet1
Dim columnToSearch As String: columnToSearch = "A"
Dim iniRowToSearch As Integer: iniRowToSearch = 2
Dim LSearchRow As Long 'As far as it is not clear the number of rows you will be considering, better relying on the long type
Dim maxRowToSearch As Long: maxRowToSearch = 2000 'There are lots of rows, so better setting a max. limit
If (Not IsEmpty(targetValue)) Then
For LSearchRow = iniRowToSearch To Sheets(sheetToSearch).Rows.Count
'If value in the current row (in columnToSearch in sheetToSearch) equals targetValue, copy entire row to LCopyToRow in sheetTarget
If Sheets(sheetToSearch).Range(columnToSearch & CStr(LSearchRow)).Value = targetValue Then
'Select row in Sheet1 to copy
Sheets(sheetToSearch).Rows(LSearchRow).Copy
'Paste row into Sheet2 in next row
Sheets(sheetTarget).Rows(LCopyToRow).PasteSpecial Paste:=xlPasteValues
Sheets(sheetTarget).Rows(LCopyToRow).PasteSpecial Paste:=xlFormats
'Move counter to next row
LCopyToRow = LCopyToRow + 1
End If
If (LSearchRow >= maxRowToSearch) Then
Exit For
End If
Next LSearchRow
'Position on cell A3
Application.CutCopyMode = False
Range("A3").Select
End If
Exit Sub
Err_Execute:
结束子
我喜欢将每一行从 A 列复制并粘贴到 H 列
【问题讨论】:
标签: vba