這應該工作。只需將Sheet1和Sheet2更改爲您擁有的sheetname即可
Option Explicit
Private Sub FindTextAndCopyToNewWS()
Dim ws As Worksheet, targetWks As Worksheet
Dim FindString As Variant
Dim rng As Range, sourceColumn As Range, targetColumn As Range
Dim lastCol As Long, lColumn As Long
Set ws = ThisWorkbook.Worksheets("Sheet1")
FindString = InputBox("Search for value")
If Trim(FindString) <> "" Then
Set rng = ws.Cells.Find(_
What:=FindString, _
LookIn:=xlValues, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False)
If Not rng Is Nothing Then
Set sourceColumn = ThisWorkbook.Worksheets("Sheet1").Columns(rng.Column)
Set targetWks = ThisWorkbook.Worksheets("Sheet2")
lastCol = targetWks.Cells(1, targetWks.Columns.Count).End(xlToLeft).Column
If targetWks.Cells(1, 1) = "" Then
Set targetColumn = ThisWorkbook.Worksheets("Sheet2").Columns(lastCol)
Else
Set targetColumn = ThisWorkbook.Worksheets("Sheet2").Columns(lastCol + 1)
End If
sourceColumn.Copy Destination:=targetColumn
Else
MsgBox "Nothing found"
End If
End If
End Sub
感謝Niclas。但是如果我們想要搜索並複製多件事情呢?有沒有我們可以使用的excel公式?理想情況下,每次使用搜索時,都應將搜索添加到新工作表的後續列中。 –
因此,每次搜索水果或蔬菜時,都應將整個欄目複製到工作表2並在現有工具之後添加複製的副本? – Niclas
是的,這是正確的。我修改了問題以顯示輸出示例。 –