Solved

Macro code help needed, please

Posted on 2011-03-22
6
149 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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Introduction While answering a recent question (http:/Q_27311462.html), I created an alternative function to the Excel Concatenate() function that you might find useful.  I tested several solutions and share the results in this article as well as t…
This tutorial explains how to create a series of drop-down lists that are dependent upon prior selections to guide (“force”) the user to make the correct selection and reduce data errors within Microsoft Excel. Excel 2010 was used for this tutorial;…
The viewer will learn how to use a discrete random variable to simulate the return on an investment over a period of years, create a Monte Carlo simulation using the discrete random variable, and create a graph to represent the possible returns over…
This Micro Tutorial will demonstrate how to use a scrolling table in Microsoft Excel using the INDEX function.

708 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

17 Experts available now in Live!

Get 1:1 Help Now