John,
Quote:
|
Someone once said it was better to have a serries of small macros linked rather than one big Macro and it is certainly easier to edit and debug smaller chunks.
|
Yes, within reason, I try to break a large procedure down into smaller, logical components.
Quote:
|
How can I only select cells that actually have data in them?
|
There are several ways to determine the last used row of a range - some of which are more reliable than others. My weapon of choice is this function:
Code:
Public Function Get_Last_Row(ByVal rngToCheck As Range) As Long
Dim rngLast As Range
Set rngLast = rngToCheck.Find(what:="*", searchorder:=xlByRows, searchdirection:=xlPrevious)
If rngLast Is Nothing Then
Get_Last_Row = rngToCheck.Row
Else
Get_Last_Row = rngLast.Row
End If
End Function
You can pass in the cells of the entire worksheet, or particular areas, and it will tell you the last row containing data or a formula. eg.
Code:
Sub test()
'what is the last used row in the entire sheet?
MsgBox Get_Last_Row(Sheet1.Cells)
'what is the last used row in the 2nd column?
MsgBox Get_Last_Row(Sheet1.Columns(2))
'what is the last used row in the range E1:N30?
MsgBox Get_Last_Row(Sheet1.Range("E1:N30"))
End Sub
When you are automating a process in Excel using VBA, you will find that 99% of the time you don't need to activate or select objects to manipulate or use them. For example, if you want to copy range A1:A10, you can just copy it - there's no need to select it first.
Code:
Sub BadExample()
'macro recorder style code
Sheets("Sheet1").Select
Range("A1:A10").Select
Selection.Copy
End Sub
Sub GoodExample()
'we can just use
Worksheets("Sheet1").Range("A1:A10").Copy
End Sub
Selecting cells will introduce buggy behaviour into your code and slow it down so, as a rule of thumn, try to avoid doing it.
Hope that helps...