Featured Post

Excel Macros: automating the boring stuff

Work Smarter – outsource the boring tasks to Excel Excel macros are “Excel Apps”. Some smaller, some larger, but all of them are “Apps” th...

Showing posts with label VBA Bits. Show all posts
Showing posts with label VBA Bits. Show all posts

Thursday, November 24, 2016

Excel version & Row and Column limits

If macros must run on multiple versions of Excel, care is needed not to overrun the older versions limits. Microsoft made a major change to the Row and Column limits in Excel 2007:

Until Excel 2003:
  • 65,536 Rows
  • 256 Columns
From Excel 2007
  • 1,048,576 Rows
  • 16,384 Columns
There are other changes, like unlimited number of sheets and the size of content each cell can have. All huge increases from the previous versions. Excel limits full list can be found here:

https://support.office.com/en-us/article/Excel-specifications-and-limits-CA36E2DC-1F09-4620-B726-67C00B05040F

It can be easy to cross the smaller limits, specially the 256 columns. If the macro adds data in columns, and the input is large, it can easily step over 256, crashing the macro in the process.

To avoid this, macros should check the Excel version they are running and the respective limits. This can be used to check if the limit is going to be cross and show a friendly error message to the user, instead of just crashing unexpectedly.

GetExVersion() 

This function takes no parameters and just returns the Excel version running the macro. Notice that Excel versions are numbers, not the commercial naming – Excel 2007 is 12, Excel 2016 is 16.



With this function we can define 2 more to retrieve the Row and Column limits:

GetMaxRows(nVersion”) eg: GetMaxRows (12)
GetMaxColss(nVersion”) eg: GetMaxCols (12)

Both functions receive the version number as a parameter and return the respective max row or column number (note: it is not the number of rows or columns, but the number of the last one – which is 1 less, so 255 for the last of 256 columns):




The easiest way to use this functions it to call them using the GetExVersion() function as a parameter. This way, it is complete self-sufficient – no need to provide any information to get a result:

nMaxRowsVariable = GetMaxRows(GetExVersion())


You can copy the code here:

Public Function GetExVersion() As Long
' Return Excel version number
Dim nOut As Long                            ' Declare the variables

    nOut = Val(Application.Version)         ' Get Version Number from system variable
    
GetExVersion = nOut                         ' Return result to caller

End Function

Public Function GetMaxRows(nVersion As Long) As Long
' Return the maximum number of rows
Dim nOut As Long                            ' Declare the variables

    If nVersion >= 12 Then                  ' If >= Excel 2007
        nOut = (2 ^ 20) - 1                 ' New versions limit
    Else
        nOut = 65535                        ' Older versions limit
    End If
    
GetMaxRows = nOut                           ' Return result to caller

End Function

Public Function GetMaxCols(nVersion As Long) As Long
' Return the maximum number of columns
Dim nOut As Long                            ' Declare the variables

    If nVersion >= 12 Then                  ' If >= Excel 2007
        nOut = 16383                        ' New versions limit
    Else
        nOut = 255                          ' Older versions limit
    End If
    
GetMaxCols = nOut                           ' Return result to caller

End Function

Sunday, May 15, 2016

Activating the right sheet

Changing the active sheet given its name is one of the basic tasks when writing business macros and can be very simple with this VBA Bits library function:


SetActiveSheet (sheetname) eg: SetActiveSheet ("Sheet2")

The function is quite simple:



If the sheet exists, it will make it the active sheet (the one selected in Excel and visible to the user). If not, nothing happens, and no error is generated - it just does nothing, retaining whichever sheet is already active on the Excel file.

How does it knows if the given Sheetname exists? It uses the DoesSheetExists(“sheetname”) VBA Bits function detailed on an other post:


You can copy the code here:

Sub SetActiveSheet(sSheetName As String)
' Activates the desired sheet by name if the sheet exists
Dim bOut As Boolean                                                     ' Declare the variables

    bOut = False                                                        ' Default - Assume Failure
    If DoesSheetExists(sSheetName) Then Worksheets(sSheetName).Activate ' Activate sheet with given name if it exists

End Sub

Sunday, May 8, 2016

Testing if a sheet exists on the Excel file, given its name


DoesSheetExists (“sheetname”) eg: DoesSheetExists ("Sheet2")


Checking if a given sheet exists having its name is simple - iterate all existing sheets and compare each one’s name with the given one. If a match is found, the function returns a TRUE value to its called. If not, FALSE is returned and no sheet with the given name was found.



The sSheetName variable is a function parameter, supplied between () after the function name. Is is a string (text) and can either be a literal text ("Sheet1") or a variable from existing code - examples of this will be found on the next VBA Bits post, which uses this function.

The UPPER() function forces text to be uppercase, assuring the comparison is not case dependent, which is how Excel treats Worksheet names.

You can copy the code here:


Function DoesSheetExists(sSheetName As String) As Boolean
' Checks if a Sheet name exists - Returns TRUE or FALSE
Dim bOut As String, WSN As Worksheet                    ' Declare the variables

    bOut = False                                        ' Default - Assume Failure
    For Each WSN In Worksheets                          ' Loop all worksheets in current file
        If UCase(sSheetName) = UCase(WSN.Name) Then     ' Compare each sheet name with the supplied one
            bOut = True                                 ' Name Found
            Exit For                                    ' Exit loop - already found the sheet name
        End If
    Next                                                ' Loop until all sheets checked

DoesSheetExists = bOut                                  ' Return result to caller

End Function



Saturday, May 7, 2016

The VBA Bits – getting rid of “plumbing”

Copying web development ideas.


In the past, web developers used to have a very rough deal - they had to spend most of the time coding tedious tasks like locating the page element to change or just plain working around browser differences. Then, one day, libraries like JQuery arrived taking care of all this “plumbing” and allowing them to just write what they needed to do:

(from http://purencool.com/javascript-and-jquery-what-is-the-difference )
(from http://purencool.com/javascript-and-jquery-what-is-the-difference )


This approach was so successful than nowadays there are thousands of libraries to write web & mobile applications – some generic, some specialized like charting libraries. But the lesson remains: “Code your needs, not plumbing”

This blog attempts to replicate this success with the VBA Bits. Small prices of independent VBA functions that can be copied to any macro to simplify specific tasks. Just copy them to a code module on your own macro and use them to simplify tasks.