用于列出名称的VBA宏代码

时间:2012-08-16 10:10:19

标签: excel vba excel-vba for-loop

我有一张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

2 个答案:

答案 0 :(得分:5)

我建议使用AutoFilter进行复制和粘贴,因为它比循环更快。请参阅下面的示例。

我的假设

  1. 原始数据位于工作表1中,如下面的快照所示
  2. 您希望工作表2中的输出如下面的快照所示
  3. 代码(经过审查和测试)

    我已对代码进行了评论,以便您在理解代码时不会遇到任何问题。

    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
    

    <强>快照

    enter image description here

答案 1 :(得分:1)

试试这个

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