【问题标题】:Copy data into new sheet (tab)将数据复制到新工作表(选项卡)
【发布时间】:2015-02-15 08:54:45
【问题描述】:
      Sheet1                            Sheet2 (output)
      A    B   C                        A    B   C
1   Name1 100  May                1   Name1 100 May        
2   Name2 200  June               2   Name2 200 June
3   Name3      Oct                3   Name3     Oct
4   Name4 300                     4   Name4 300
5   Name5       

我想读取 B 列和 C 列中的值。如果 2 中存在任何值,则将该行拉入同一 Excel 工作簿的新工作表或选项卡中。如果 B 列和 C 列为空白,则跳过该行并移至下一行。

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    下面是cmets中的解释代码

    测试

    Sub checkNcopy()
    'Checking the last populated row
    lastRow = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
    
    counter = 2
    
    'Copying the variable Names
    for i=1 to 3
    Worksheets("Sheet2").Cells(1, i) = Worksheets("Sheet1").Cells(1, i)
    Next 
    
    For i = 2 To lastRow
    
    'Checking if one of the two columns B and C are populated or not
    If Not IsEmpty(Worksheets("Sheet1").Cells(i, 2)) Or Not IsEmpty(Worksheets("Sheet1").Cells(i, 3)) Then
    
    'If one of the two variables are populated then copying the data from sheet1 to sheet2
    for j=1 to 3
     Worksheets("Sheet2").Cells(counter, j) = Worksheets("Sheet1").Cells(i, j)
    Next
    counter = counter + 1
    End If
    
    Next
    
    End Sub
    

    【讨论】:

    • 你可以使用 .CurrentRagion() 方法和 .Copy() 方法
    【解决方案2】:

    您可以在活动范围上使用.CurrentRegion() 来获取与整个表对应的范围,以及.Copy() 方法:

    Sub CopyData()
    
    Worksheets("Sheet1").Range("A1").Activate
    
    ActiveCell.CurrentRegion.AutoFilter Field:=2, Criteria1:="<>"
    
    ActiveCell.CurrentRegion.AutoFilter Field:=3, Criteria1:="<>"
    
    ActiveCell.CurrentRegion.Copy Worksheets("Sheet2").Range("A1")
    
    End Sub
    

    稍微更合适,但可读性较差的版本是:

    Sub CopyDataxxx()
    
        Dim TargetRange As Range
    
        Worksheets("Sheet1").Activate
        Range("A1").Activate
    
        Set TargetRange = ActiveCell.CurrentRegion
    
        With TargetRange
            .AutoFilter Field:=3, Criteria1:="<>"
            .Copy Worksheets("Sheet2").Range("A1")
            .AutoFilter 'switches off AutoFilter
        End With
    
    End Sub
    

    【讨论】:

    • 您必须避免复制 B 和 C 列为空白的行
    • @NEO_mental 不,它不会复制带有空白单元格的行
    猜你喜欢
    • 1970-01-01
    • 2021-07-26
    • 2022-10-06
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-21
    相关资源
    最近更新 更多