G
Guest
I am new to VBA and Excel programming. I wanted a way of copying all the rows
from one worksheet that had real data, into another worksheet so wrote the
script below. It does work, but I would like to know if its
good/bad/indifferent/inefficient and any ways it could be improved. Hopefully
from this I will then get a better idea of how to do VBA programming:
thanks
Sub copyRowsWithData(sourceSheet As Worksheet, destinationSheet As Worksheet)
'
' Routine to copy all, and only, non-blank rows from one worksheet to another.
'
Dim nextDestinationRow As Integer ' pointer to next row to use in
destination sheet
Dim anyDataInRow As Boolean ' keeps track of any non-blank cells
in row being searched
Dim rowsWithData As Range ' holds the range that extends to
the end of the data
Dim aRow As Range
Dim aCell As Range
Set rowsWithData = sourceSheet.UsedRange.Rows
nextDestinationRow = 1
For Each aRow In rowsWithData
anyDataInRow = False
For Each aCell In aRow.Cells
If Not (IsEmpty(aCell)) Then
anyDataInRow = True
End If
Next aCell
If anyDataInRow Then
sourceSheet.Select
aRow.Copy
destinationSheet.Select
Rows(nextDestinationRow).Select
ActiveSheet.Paste
nextDestinationRow = nextDestinationRow + 1
End If
Next aRow
End Sub
Sub Macro1()
'
Call copyRowsWithData(Worksheets("Sheet1"), Worksheets("Sheet2"))
End Sub
from one worksheet that had real data, into another worksheet so wrote the
script below. It does work, but I would like to know if its
good/bad/indifferent/inefficient and any ways it could be improved. Hopefully
from this I will then get a better idea of how to do VBA programming:
thanks
Sub copyRowsWithData(sourceSheet As Worksheet, destinationSheet As Worksheet)
'
' Routine to copy all, and only, non-blank rows from one worksheet to another.
'
Dim nextDestinationRow As Integer ' pointer to next row to use in
destination sheet
Dim anyDataInRow As Boolean ' keeps track of any non-blank cells
in row being searched
Dim rowsWithData As Range ' holds the range that extends to
the end of the data
Dim aRow As Range
Dim aCell As Range
Set rowsWithData = sourceSheet.UsedRange.Rows
nextDestinationRow = 1
For Each aRow In rowsWithData
anyDataInRow = False
For Each aCell In aRow.Cells
If Not (IsEmpty(aCell)) Then
anyDataInRow = True
End If
Next aCell
If anyDataInRow Then
sourceSheet.Select
aRow.Copy
destinationSheet.Select
Rows(nextDestinationRow).Select
ActiveSheet.Paste
nextDestinationRow = nextDestinationRow + 1
End If
Next aRow
End Sub
Sub Macro1()
'
Call copyRowsWithData(Worksheets("Sheet1"), Worksheets("Sheet2"))
End Sub