Question

VBA module to find max characters for each row by column in Excel sheet

Asked by: b0lsc0tt

I am really asking this for feedback but do have a question or two that I will try to include.  I had a CSV file that I imported into Excel to be able to read and review.  The data will actually be going to a MYSQL DB but that probably doesn't matter.  There are about 15 "fields" or columns (if you think about it as Excel shows it) and 170K records or rows.

To get ready to work with the data in the DB I wanted an idea of how many characters were in each field.  Specifically I wanted to know the max length I would need for a DB field.  Excel spaced the columns nicely but I wasn't sure how to find out how many characters each column needed or required.  So I used the VB Editor and made a little routine.  The code is below (see snippet).  It actually appears to work so I am feeling pretty proud (VBA is something I don't like to use at all and find very frustrating to work in even though I like VB, or at least vbscript).

My main question is do you see any problems or a way to do it better?  Specifically how I reference the cells, columns, rows and "range"?  I think the logic is about as good as can be but working with the "object" of a sheet and all of its elements, properties, etc is where I just lack expertise (and MS' Help seems especially hard to use as reference).

I had to use "CurrentRegion" to get the part of the sheet that was used (i.e. ignore the blank or unused columns to the right and rows below) but I didn't think I had to use it before.  I have only made couple but thought there was an easier way to select just the used cells and was frustrated until I found the CurrentRegion property(?).  Is there another that is often used or is the only other option specifically using cell references to set the range?

The only "bug" that I found when running it was the max character amount was place on the second row down, not the very lowest row.  Any idea why looking at my For loop and the line below?

Finally why couldn't I use For Each to loop through the Rows or Columns "collection"?  Specifically the columns since I changed the For Each loop for the rows because I wanted a "counter."  I was getting errors though and didn't understand why but they left when I changed to a "For i = 1" loop.

BTW, was I correct to start the loop at 1?  I couldn't find that for sure but thought the count of columns/rows started at 1.  Just was hoping to verify that.

Thanks!  Let me know if there is a question about this or you need any more info.

bol

Attribute VB_Name = "Module1"
Sub getMaxLen()
    Dim col, i, line
    Dim myRange As Range
    Worksheets("Sheet1").Activate
    Set myRange = ActiveCell.CurrentRegion
    'MsgBox (myRange.Rows.Count & " - " & myRange.Columns.Count)
    'Exit Sub
    For col = 1 To myRange.Columns.Count
        If col > 16 Then Exit Sub
        'MsgBox (Cells(1, col).Value)
        'If Cells(1, col).Value = "" Then Exit Sub
        i = 0
        For line = 1 To myRange.Rows.Count
            If Len(Cells(line, col).Value) > i Then i = Len(Cells(line, col).Value)
        Next
        Worksheets("Sheet1").Cells((line + 1), col).Value = i
    Next
End Sub

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-10-08 at 16:07:44ID24797925
Tags

VBA

,

VB

,

Excel

,

VB for Applications

,

module

,

sub

Topics

Microsoft Excel Spreadsheet Software

,

Visual Basic Programming

,

VB Script

Participating Experts
2
Points
500
Comments
10

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. VBA
    I AM WRITING IN VBA AND I NEED IT TO USE THE DATA IN A CELL AND ADD OR SUBTACT BY SOME SET NUMBERS. MY PROMBLEM IS THAT I DO NOT NOW HOW TO PULL THE DATA OFF THE SHEET IN EXCEL INTO VBA.
  2. Set EXCEL Sheet to Text with VBA
    What is the code to set a Sheet to TEXT with VBA and then back to default? BY default it is General. What I mean by text is that all the cells in the sheet are text cells. They don't do any auto formatting of numbers etc.
  3. Protecting all sheets and cells using VBA
    I'd like to for EVERY Sheet apart from the CURRENT SHEET 1. Select all the cells 2. Set Format Cells-->Protection--> Locked and Hidden = True 3. Do Tools-->Protection-->Protect Sheet and have a password entered (I'd like the password to be the same for e...
  4. Autofocus a Cell (VBA/Excel)
    What is the VBA code to put the focus on a cell as soon as the worksheet opens. Thanks
  5. Copy Range of Cells to Another Sheet Using VBA
    How do I with VBA copy of range of cell values to another sheet in the same workbook? Thanks, MV

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: zorvekPosted on 2009-10-08 at 16:15:57ID: 25531201

Pretty good start. A few tweaks. I declare every variable on a separate line so I know what each is. You want to avoid Variant declarations (the default) whenever possible as they are inefficient. And you want to avoid selecting objects like sheets.

Sub getMaxLen()
   Dim col As Long
   Dim i As Long
   Dim line As Long
   Dim myRange As Range
   With Worksheets("Sheet1")
       Set myRange = .[A1].CurrentRegion
       'MsgBox (myRange.Rows.Count & " - " & myRange.Columns.Count)
       'Exit Sub
       For col = 1 To myRange.Columns.Count
           'MsgBox (Cells(1, col).Value)
           'If Cells(1, col).Value = "" Then Exit Sub
           i = 0
           For line = 1 To myRange.Rows.Count
               If Len(Cells(line, col).Value) > i Then i = Len(Cells(line, col).Value)
           Next
           .Cells((line + 1), col).Value = i
       Next
   End With
End Sub

Kevin

 

by: b0lsc0ttPosted on 2009-10-08 at 16:30:19ID: 25531289

Thanks!

>> You want to avoid Variant declarations (the default) whenever possible as they are inefficient. <<
I tried doing that but just added "As Long" to the first Dim line.  E.g.

Dim col, i, line As Long

It seemed I removed it because I was getting some error.  Is the syntax wrong to do them at once like I was trying or is it something else?  Or should that have worked?

>> And you want to avoid selecting objects like sheets. <<

Are you refering to the line below when you say selecting an object?

Worksheets("Sheet1").Activate

I just wanted to clarify because I wasn't really sure what you meant there, although it makes sense.  Or was it not using With as you did to work with the worksheet?

Thanks!  Let me look closer and try the changes?  Any thoughts about the "side" questions?  If I got carried away I can open a new question for them if I need an answer.  I was just thinking they may be on topic and a quick answer so I included them.

bol

 

by: leonstrykerPosted on 2009-10-08 at 19:56:29ID: 25532060

>Dim col, i, line As Long

This make the last variable as Long while the others are still Variant data types. It is also a good idea to standardize variable declaration:

Dim intCol As Integer
Dim lngLine As Long

>Or should that have worked?

If you were getting an error, it meant you where using that variable in a bad way. Hard to say exactly without seeing the error itself.

>Are you refering to the line below when you say selecting an object?

Yes he is.

I would also avoid using single line If statements as they become very easy to misread if there are multiple decisions to be made.

 

by: zorvekPosted on 2009-10-08 at 20:55:20ID: 25532208

Don't use Integer. It is still legal syntax but is stored as a long anyway. Extra code is generated to check for overflows.

Always define each variable separately. Good programming practice. Also note that the VB runtime initializes all variables to zero, false, or an empty string.

Don't select anything in the Excel object model: workbooks, worksheets, cells, etc. You can (almost) always refer to them through the Excel object model and you should never have to use "active" object references unless you are interacting with the user. There are two reasons for this: it slows your code down and it changes the user's selection.

Single line If statements are common and I use them frequently but only when there is one conditional statement and no Else clause. I find that single line If statements make the code a little easier to read.

You can use UsedRange instead of CurrentRegion but UsedRange will return the smallest rectangle encompassing all of the used cells on the worksheet. CurrentRegion is a good way to find the range of used cells given one cell in that range, assuming, of course, that there are no other regions touching the one you want.

All row and column indices start at 1.

Here is a more tight version of your macro:

Sub GetMaxLen()

    Dim Column As Range
    Dim Cell As Range
    Dim SummaryRow As Range
    Dim MaxLength As Long
   
    With Worksheets("Sheet1")
        Set SummaryRow = .UsedRange.Rows(.UsedRange.Rows.Count + 1)
        For Each Column In .UsedRange.Columns
            MaxLength = 0
            For Each Cell In Column.Cells
                If Len(Cell.Text) > MaxLength Then MaxLength = Len(Cell.Text)
            Next Cell
            Intersect(Column.EntireColumn, SummaryRow) = MaxLength
        Next Column
    End With

End Sub

Kevin

 

by: leonstrykerPosted on 2009-10-09 at 06:18:32ID: 25534623

>I find that single line If statements make the code a little easier to read.

I find them much harder to read especially if you have nested If statements, and it was considered bad coding practice in several companies I worked for. IIf functions in code were also considered a 'no no', mainly because both portions are evaluated in any case and in certain situations this would through an error.

Leon

 

by: b0lsc0ttPosted on 2009-10-09 at 13:54:02ID: 25538799

I need to work on a complete response but am very pleased with the replies. Thanks especially Kevin!

leonstryker,
I appreciate your comment about the If statement. I completely agree with cases where Else is used and other complicated cases. I also understand company practices may prohibit it but I was using it and thinking like Kevin described. For a situation where it is If with the one condition and one line to be used. Basically it saves me two lines and the unneeded End If. Point taken though and I appreciate the feedback.

All,
I hadn't realized but there were some issues with what I was doing. I started to see what you both meant when I ran the Sub with my cursor in a cell all the way at the bottom of the data (actually 2 rows below). The Sub only looked at the first line it seemed and total just that row. Using [A1] and the other changes seemed to make the difference. Thanks!

Interesting about UsedRange and thanks for that other code. I couldn't understand how Intersect worked. Is it the method that can also be used after an "expression" (according to the Help)? Is it basically just finding the cell in the SummaryRow?

The newer version seemed to take about 3 times as long in the sheet. Any ideas why? I made the changes and never got an error adding the declarations so I must've messed something else up when I tried to do them before. The code works great with either version and I appreciate the corrections. I will review this closer but I think everything has been answered very well. Just curious about the difference in running time, especially since the slower is the most compact code (the last code posted) and the difference is noticeable.

Thanks! I will have time in a few hours to look at this again.

bol

 

by: zorvekPosted on 2009-10-09 at 14:36:50ID: 25539092

Intersect returns the intersection of two ranges.

Not sure why the second version is slower. See if this is faster:

Sub GetMaxLen()

    Dim Column As Range
    Dim Cell As Range
    Dim SummaryRow As Range
    Dim MaxLength As Long
   
    Application.ScreenUpdating = False
    With Worksheets("Sheet1")
        Set SummaryRow = .UsedRange.Rows(.UsedRange.Rows.Count + 1)
        For Each Column In .UsedRange.Columns
            MaxLength = 0
            For Each Cell In Column.Cells
                If Len(Cell.Text) > MaxLength Then MaxLength = Len(Cell.Text)
            Next Cell
            Intersect(Column.EntireColumn, SummaryRow) = MaxLength
        Next Column
    End With
    Application.ScreenUpdating = True

End Sub

Kevin

 

by: b0lsc0ttPosted on 2009-10-12 at 19:00:15ID: 25556464

It did not seem to make a difference to add the lines for ScreenUpdating.  If there was one it was minor.

I did find out something interesting though.  There did seem to be a difference when I changed my old routine (with your modifications) to use .Text instead of .Value.  Just the line for the If but it noticeably slowed it down.

Does that make sense?  How would you explain the difference between the 2 properties?  I did notice the totals were different in 3 columns depending on what I used.  I am not sure but it seemed .Text was more accurate.

I do have my answer though so I can finalize this if it has reached that point.  I am very please with what I have and not sure I care to investigate this much more.  If any are interested then I won't mind but I also will be very please if this is closed now.

If there is a question with what I have said then let me know.  Thanks for everything!

bol

 

by: zorvekPosted on 2009-10-12 at 21:27:11ID: 25556954

The Text property returns a string containing the formatted value. The Value property returns the cell value in it's internal form. So it makes sense that the Text property consumes more time than the Value property.

Kevin

 

by: b0lsc0ttPosted on 2009-10-13 at 11:43:58ID: 31639053

Thanks for the great help and info!

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...