excel - 如何使用特定单词复制 Excel 中的行并将其粘贴到另一个 Excel 工作表?

标签 excel vba

我检查了很多不同的帖子,但似乎找不到我正在寻找的确切代码。另外,我以前从未使用过 VBA,因此我尝试从其他帖子中获取代码并输入我的信息以使其正常工作。还没有运气。在工作中,我们有一个 Excel 薪资系统。我正在尝试搜索我的名字“Clarke,Matthew”,然后复制该行并将其粘贴到我保存在桌面上的工作簿“总小时数”

最佳答案

代码

Sub Sample()
    Dim wb1 As Workbook, wb2 As Workbook
    Dim ws1 As Worksheet, ws2 As Worksheet
    Dim copyFrom As Range
    Dim lRow As Long '<~~ Not Integer. Might give you error in higher versions of excel
    Dim strSearch As String
    
    Set wb1 = ThisWorkbook
    Set ws1 = wb1.Worksheets("yourSheetName")
    
    strSearch = "Clarke, Matthew"
    
    With ws1

        '~~> Remove any filters
        .AutoFilterMode = False

        '~~> I am assuming that the names are in Col A
        '~~> if not then change A below to whatever column letter
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
       
        With .Range("A1:A" & lRow)
            .AutoFilter Field:=1, Criteria1:="=*" & strSearch & "*"
            Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
        End With
        
        '~~> Remove any filters
        .AutoFilterMode = False
    End With
    
    '~~> Destination File
    Set wb2 = Application.Workbooks.Open("C:\Sample.xlsx")
    Set ws2 = wb2.Worksheets("Sheet1")
    
    With ws2
        If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
            lRow = .Cells.Find(What:="*", _
                          After:=.Range("A1"), _
                          Lookat:=xlPart, _
                          LookIn:=xlFormulas, _
                          SearchOrder:=xlByRows, _
                          SearchDirection:=xlPrevious, _
                          MatchCase:=False).Row
        Else
            lRow = 1
        End If
    
        copyFrom.Copy .Rows(lRow)
    End With
    
    wb2.Save
    wb2.Close
End Sub

快照

enter image description here

关于excel - 如何使用特定单词复制 Excel 中的行并将其粘贴到另一个 Excel 工作表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11631363/

相关文章:

excel - 保存前仅计算事件工作簿

vba - Excel VBA 从中央服务器获取命令的最佳方法

vba - 使用 VBA 从 Excel 数据创建 Outlook 约会

excel - 在一台计算机上打开工作簿错误代码 32809,但在另一台计算机上打不开

vba - 让 vba 在继续之前等待

c# - 将数据插入到excel C#中的特定单元格

excel - VBA:在新工作表上创建数据透视表

vba - 出现编译错误: User-defined type not defined when working to make an old 32-bit template into a Word 2012 64-bit template

excel - 统计按一定分隔符分割的数据条数

Excel TRIM 函数错误