Solved

Macro code help needed, please

Posted on 2011-03-22
6
150 Views
Last Modified: 2012-05-11
I am using the code below tied to a command button at the top of the worksheet.  The code autofits all columns and puts a total line at the bottom, 1 row after the last row of data.  This worksheet receives data that is exported from access, so the amount of rows can vary.  The column headers begin in row 4.

It works great as long as there is more than 1 row of data.  If there is only 1 row of data (or no data rows)  the user receives a  "Run time error 1004, Application Defined  or Object Defined Error"  and line 27 is highlighted in code.   How can I correct this please?

Another user on this site provided me with this great macro... I am hoping a small tweak will fix this problem.

Thanks!


Sub DoTasks()

 Dim cell As Range
    Dim total As Long
    Dim rows_in_col As Long
    
    Dim header As Range
 'Find cells in header
    If Range("A4") = "" Then
        'May only be one cell in header
        Set header = Range("A4")
    Else
        Set header = Range(Range("A4"), Range("A4").End(xlToRight))
    End If
    
    'Find the max row
    For Each cell In header
        rows_in_col = Range(cell, cell.End(xlDown)).Count
        If rows_in_col > total Then
            total = rows_in_col
        End If
    Next cell
    
    'Add the sum column two rows below max
    For Each cell In header
        If cell.Column = 11 Or cell.Column = 12 Then
            Cells(cell.Row + total + 1, cell.Column).Formula = "=@subtotal(9," & Range(cell, cell.End(xlDown)).Address & ")"
        End If
    Next cell
    
    'Same command as double clicking the border.
    Range("A:M").EntireColumn.Autofit
    
    Cells(header.Row + total + 1, 1).Activate


End Sub

Open in new window

0
Comment
Question by:snyperj
  • 3
  • 2
6 Comments
 
LVL 19

Expert Comment

by:akoster
ID: 35189712
snyperj,

when no data is added, the total variable (the number of rows) will be the number of available rows in the worksheet (eg. 1048573)
When you add 1 to it (as in line 34), it won't fit any more.

A better way would be to use

total = usedrange.rows.count

Open in new window


instead of lines 17 up to 22.
0
 
LVL 6

Expert Comment

by:FernandoFernandes
ID: 35189771
I would fix the code by changing more things... but these changes below already do the job:
Sub DoTasks()

 Dim cell As Range
    Dim total As Long
    Dim rows_in_col As Long
    Dim header As Range
 'Find cells in header
    If Range("A4") = "" Then
        'May only be one cell in header
        Set header = Range("A4")
    Else
        Set header = Range(Range("A4"), Range("A4").End(xlToRight))
    End If
    
    If header Is Nothing Then Exit Sub
    
    'Find the max row
    For Each cell In header
        rows_in_col = Range(cell, cell.End(xlDown)).Count
        If rows_in_col > total And rows_in_col < Cells.Rows.Count - 5 Then
            total = rows_in_col
        End If
    Next cell
    
    If total > 1 Then
        Range(Cells(header.Row + total + 1, 1), Cells(header.Row + total + 1, header.Columns.Count)).FormulaR1C1 = "=SUM(R5C:R[-2]C)"
    End If
    
    'Same command as double clicking the border.
    Range("A:M").EntireColumn.AutoFit
    
    Cells(header.Row + total + 1, 1).Activate

End Sub

Open in new window

0
 
LVL 6

Expert Comment

by:FernandoFernandes
ID: 35189820
I am also against determining last row using a loop and the .End method of the range object from the top.
this is why I had to fix the condition inside the loop.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:snyperj
ID: 35189868

hmmm.. thanks for the efforts!

akoster - your change raises a new error, Runtime 424 Object Required and highlights the new line of code yo gave which I inserted instead of lines 17 - 22

Fernando- your change puts a total on every column.  How can I get it back to just the columns that were being totaled?  (11 & 12)

Thanks!
0
 
LVL 6

Accepted Solution

by:
FernandoFernandes earned 500 total points
ID: 35189909
change this line 26 only:
Range(Cells(header.Row + total + 1, 11), Cells(header.Row + total + 1, 12)).FormulaR1C1 = "=SUM(R5C:R[-2]C)"

Open in new window

0
 

Author Closing Comment

by:snyperj
ID: 35189959
Success!   Thank you.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Drop Down List with Unique/Distinct Values (enhancing the Combo-Box with a few steps and a little code) David miller (dlmille) Intro Have you ever created a data validation list from a database field or spreadsheet column (e.g., Zip Codes or Co…
Approximate matching with VLOOKUP and MATCH seems to me to be a greatly under-used technique, and one which is vital for getting good performance out of large lookups. Until recently I would always have advised using an exact match for simplicity an…
The viewer will learn how to create two correlated normally distributed random variables in Excel, use a normal distribution to simulate the return on different levels of investment in each of the two funds over a period of ten years, and, create a …
This Micro Tutorial will demonstrate in Microsoft Excel how to add style and sexy appeal to horizontal bar charts.

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now