我有 2 个搜索单元 B2 和 B3。我希望他们从名为 fakturor 的表中查找和写入数据。我与一个 B2 一起工作得很好,可以在工作表 fakturor 的 B 列中进行搜索。但是,如果我希望 B2 和 B3 中的值在同一行上都是正确的,我该怎么办?
我的剧本
Sub SearchForString()
With Worksheets("Budget")
Rows("11:" & .Rows.Count).Clear
End With
Dim LCopyToRow As Integer
On Error GoTo Err_Execute
'Start copying data to row 2 in Sheet2 (row counter variable)
LCopyToRow = 11
Dim sheetTarget As String: sheetTarget = "Budget"
Dim sheetToSearch As String: sheetToSearch = "Fakturor"
'Value in Budget!B2 to be searched in Fakturor
Dim targetValue As String: targetValue = Sheets(sheetTarget).Range("B2").Value
'Value in Column B will be searched
Dim columnToSearch As String: columnToSearch = "B"
Dim iniRowToSearch As Integer: iniRowToSearch = 1
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
'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:
MsgBox "Ett fel har inträffat, prata med Per"
End Sub