我是VBA编码的新手,我正在研究一个项目,从工作簿的所有工作表中搜索一个字符串(例如1207_Stackoverflow_com),然后调用它WB1并选择代码搜索的列并将其粘贴到另一个工作簿上,如WB2 . 每次代码搜索包含该字符串的行时,都会将该列复制到WB2中的下一个工作表 . 我试过但是代码出错了 . 所有帮助表示赞赏 . 下面是我构建的代码(我知道它是一个粗略的代码,随意使用你的编码风格来教育我)

Sub SearchAndPaste()

    Dim WB1 As Workbook, WB2 As Workbook
    Dim myRng As Variant, mFind As Variant
    Dim rng As Range
    Dim Col1

    Set WB1 = Workbooks.Open("Path of workbook")

    WB2 = ThisWorkbook
    mDate = WB2.Sheets("Sheet1").Range("J3").Value


    Set rng = ThisWorkbook.Sheets("Sheet1").Range("A1")
    Set rng = WB2.Worksheets.Range("A2:CJ2")
    Cells(myRng.Row, myRng.Column).Select
    Col1 = Selection.Column

    For Each sh In ActiveWorkbook.Worksheets
        ' Find first instance on sheet
        Set myRng = rng.Find(What:=Str(mFind), After:=sh.Cells(1, 1), _
            LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
            SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
        If Not cl Is Nothing Then
            ' if found, remember location
            Cells(myRng.Row, myRng.Column).Select
            Col1 = Selection.Column
            ' Copy column
            Do

                ' find next instance
                Set Col1 = sh.Cells.FindNext(After:=cl)
                ' repeat until back where we started
            Loop Until FirstFound = Col1.Address
        End If
    Next
End Sub