Copy only cells with data within a range using VBA

Drewmyster

Board Regular
Joined
May 16, 2007
Messages
150
Office Version
  1. 365
Platform
  1. Windows
Here is the code I use;

Private Sub CommandButton1_Click()
Range("G4:G200").Copy
End Sub

If cells are blank how do I remove them from being copied?
 

Excel Facts

What is the last column in Excel?
Excel columns run from A to Z, AA to AZ, AAA to XFD. The last column is XFD.
What is in cells G4:G200...
Formulas or constants?
What type of values...text or numbers?
 
Upvote 0
Please try the following on a copy of your workbook:
VBA Code:
Private Sub CommandButton1_Click()
    Dim c As Range, r As Range
    For Each c In Range("G4:G200").SpecialCells(xlCellTypeFormulas)
        If c <> "" Then
            If r Is Nothing Then Set r = c Else Set r = Union(r, c)
        End If
    Next c
    
    r.Copy

End Sub
 
Upvote 0
Please try the following on a copy of your workbook:
VBA Code:
Private Sub CommandButton1_Click()
    Dim c As Range, r As Range
    For Each c In Range("G4:G200").SpecialCells(xlCellTypeFormulas)
        If c <> "" Then
            If r Is Nothing Then Set r = c Else Set r = Union(r, c)
        End If
    Next c
   
    r.Copy

End Sub
Thanks that has worked, I just noted that one cell to copy will always be text and not a formula, is there a way to include this in the same macro?
 
Upvote 0
Sure, just lose the special cells part:
VBA Code:
Private Sub CommandButton1_Click()
    Dim c As Range, r As Range
    For Each c In Range("G4:G200")
        If c <> "" Then
            If r Is Nothing Then Set r = c Else Set r = Union(r, c)
        End If
    Next c
    
    r.Copy

End Sub
 
Upvote 0

Forum statistics

Threads
1,216,101
Messages
6,128,842
Members
449,471
Latest member
lachbee

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top