以下是一个示例 VBA 代码,可以循环遍历工作簿中的每个工作表,并查找包含 '软件工程' 的单元格。如果找到,则将包含该单元格的整行复制到当前工作表。

Sub FindAndCopyRows()
    Dim ws As Worksheet
    Dim searchRange As Range
    Dim foundCell As Range
    Dim copyRange As Range
    Dim lastRow As Long
    Dim i As Long
    
    'Loop through each worksheet
    For Each ws In ThisWorkbook.Worksheets
        'Set the search range to the entire sheet
        Set searchRange = ws.Cells
        
        'Find the first occurrence of '软件工程'
        Set foundCell = searchRange.Find('软件工程', LookIn:=xlValues)
        
        'If a match is found, loop through each match and copy the entire row
        Do While Not foundCell Is Nothing
            'Set the range to copy (the entire row)
            lastRow = ws.Cells(ws.Rows.Count, foundCell.Column).End(xlUp).Row
            Set copyRange = ws.Range(ws.Cells(foundCell.Row, 1), ws.Cells(lastRow, ws.Columns.Count))
            
            'Copy the range to the active sheet
            copyRange.Copy Destination:=ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
            
            'Find the next occurrence of '软件工程'
            Set foundCell = searchRange.FindNext(foundCell)
        Loop
    Next ws
End Sub

请注意,此代码假定您要将行复制到活动工作表。如果要将行复制到特定工作表,请更改 Destination 行中的代码。此外,此代码还假定您正在查找包含 '软件工程' 的文本,如果您要查找其他文本,请将 '软件工程' 更改为所需的文本。

为了提高代码效率,您可以考虑以下优化措施:

  • 使用 Application.ScreenUpdating = FalseApplication.Calculation = xlCalculationManual 禁用屏幕更新和自动计算,减少运行时间。
  • 使用 UsedRange 或其他方法确定实际使用的单元格区域,缩小搜索范围。
  • 使用 FindNext 方法逐个查找匹配项,而不是每次都重新搜索整个工作表。
  • 避免使用 ActiveSheet,使用具体的 Worksheet 对象提高代码可读性和可维护性。

通过以上优化措施,可以显著提高代码效率,缩短运行时间,提升程序性能。


原文地址: http://www.cveoy.top/t/topic/l44u 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录