-1

I have a column full of either numbers or blanks, except Excel doesn't treat them as blanks because they are actually a formula like =IFERROR(A1+B1,""). I would like a macro to copy this column to a staging area, delete any cells that are "blank", and copy the trimmed-down column to a third location.

Example:

Sheet1!C2:C8 contains {1,"","",4,5,"",8}

This should be copied to Sheet2, trimmed down to contain {1,4,5,8}, and then pasted in row B of Sheet3.

4
  • 1
    Hint: after copying, With Worksheets("Sheet2").Range("C2:C8"), .Value = .Value, End With.
    – BigBen
    Commented Jul 9 at 19:39
  • Thank you. I think the part I'm struggling with is identifying the empty cells.
    – Tim Starr
    Commented Jul 9 at 19:42
  • 1
    Lots of approaches. For example, using Range.AutoFilter, or Range.SpecialCells(xlCellTypeBlanks). The hint is that, after you call .Value = .Value, the empty cells are truly empty.
    – BigBen
    Commented Jul 9 at 19:46
  • 1
    You can also use a filter function if you're simply trying to get results and care less about it being done via vba. =Filter(Sheet1!C2:C8, Sheet1!C2:C8 <>"")
    – Mark S.
    Commented Jul 9 at 20:10

1 Answer 1

0

If you add the VBA-Better-Array class to your VBA project, you can use this code to extract the values from Sheet1, perform the filter inside VBA (without needing a staging sheet) and then write the output to Sheet3


Sub FilterAndCopyRange()

    'Set source and destination
    Dim RngSource As Range
    Set RngSource = ThisWorkbook.Sheets("Sheet1").Range("C2:C8")
    
    Dim RngDestination As Range 'Note that we only pass the top-left cell of where we want the data to be written.
    Set RngDestination = ThisWorkbook.Sheets("Sheet3").Range("B1")
    
    'Create BetterArray from source range
    Dim Arr As BetterArray
    Set Arr = New BetterArray
    Arr.FromExcelRange RngSource
    
    'Filter out blank values
    Arr.Filter ""
    
    'Write the value back to the sheet
    Arr.ToExcelRange RngDestination

End Sub

Not the answer you're looking for? Browse other questions tagged or ask your own question.