0

我有一个 Excel 工作表,其中名称为一列,其工作时间为下一列中的值。

我想将值大于 40 的名称复制到新工作表中,并且列中没有任何空格。新的工作表应该有名字和工作时间;值列中的任何文本都应被忽略。

Sub CopyCells()
    Dim sh1 As Worksheet, sh2 As Worksheet 
    Dim j As Long, i As Long, lastrow1 As Long 

    Set sh1 = Worksheets("Sheet1") 
    Set sh2 = Worksheets("Sheet2") 
    lastrow1 = sh1.Cells(Rows.Count, "F").End(xlUp).Row 

    For i = 1 To lastrow1 
        If sh1.Cells(i, "F").Value > 20 Then 
            sh2.Range("A" & i).Value = sh1.Cells(i, "F").Value 
        End If 
    Next i 
End Sub
4

2 回答 2

5

I would recommend using AutoFilter to copy and paste as it is faster than looping. See the example below.

My Assumptions

  1. Original Data is in Sheet 1 as shown the snapshot below
  2. You want the output in Sheet 2 as shown the snapshot below

CODE

I have commented the code so that you will not have a problem understanding it.

Option Explicit

Sub Sample()
    Dim wsI As Worksheet, wsO As Worksheet
    Dim lRow As Long
    
    '~~> Set the input sheet
    Set wsI = Sheets("Sheet1"): Set wsO = Sheets("Sheet2")
    
    '~~> Clear Sheet 2 for output
    wsO.Cells.ClearContents
    
    With wsI
        '~~> Remove any existing filter
        .AutoFilterMode = False
        
        '~~> Find last row in Sheet1
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
        
        '~~> Filter Col B for values > 40
        With .Range("A1:B" & lRow)
            .AutoFilter Field:=2, Criteria1:=">40"
            '~~> Copy the filtered range to Sheet2
            .SpecialCells(xlCellTypeVisible).Copy wsO.Range("A1")
        End With
        
        '~~> Remove any existing filter
        .AutoFilterMode = False
    End With
    
    '~~> Inform user
    MsgBox "Done"
End Sub

SNAPSHOT

enter image description here

于 2012-08-16T10:26:23.970 回答
1

Try rhis

Sub CopyCells()
    Dim sh1 As Worksheet, sh2 As Worksheet
    Dim j As Long, i As Long, lastrow1 As Long
    Set sh1 = Worksheets("Sheet1")
    Set sh2 = Worksheets("Sheet2")
    lastrow1 = sh1.Cells(Rows.Count, "F").End(xlUp).Row
    j = 1
    For i = 1 To lastrow1
        If Val(sh1.Cells(i, "F").Value) > 20 Then
            sh2.Range("A" & j).Value = sh1.Cells(i, "F").Value
            j = j + 1
        End If
    Next i
End Sub
于 2012-08-16T10:24:49.843 回答