Copy a range to a new workbook with a condition

前端 未结 1 525
离开以前
离开以前 2021-01-26 17:22

\"database\"

Hi all! I have been trying to make vba code for the following purpose: copy a range of a workbook (sc

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-26 17:55

    A very useful way of ignoring blanks - without looping - is to use SpecialCells. The code below is probably a little lengthier than needed for your question but it is written so that

    1. It can be adapted to other sheets
    2. It will copy non-blanks from row 2 whether they are values and/or formulae
    3. In absence of seeing your code it copies to a new workbook

    code

    Sub CopyEm()
    Dim WB As Workbook
    Dim ws As Worksheet
    Dim rng1 As Range
    Dim rng2 As Range
    Dim rng3 As Range
    Set ws = Sheets(1)
    On Error Resume Next
    Set rng1 = ws.Rows(2).SpecialCells(xlConstants)
    Set rng2 = ws.Rows(2).SpecialCells(xlFormulas)
    If rng1 Is Nothing Then
    Set rng3 = rng2
    ElseIf rng2 Is Nothing Then
    Set rng3 = rng1
    Else
    Set rng3 = Union(rng1, rng2)
    End If
    If rng3 Is Nothing Then Exit Sub
    On Error GoTo 0
    Set WB = Workbooks.Add
    rng3.Offset(-1, 0).Copy WB.Sheets(1).[a1]
    rng3.Copy WB.Sheets(1).[a2]
    End Sub
    

    0 讨论(0)
提交回复
热议问题