When you copy data to Excel, from another application, blank cells in the data can cause problems. Everything looks okay, at first glance, but the database blank cells don’t behave like other blank cells in the workbook. See how to fix blank Excel cells copied from a database, or created within Excel.
Continue reading “Fix Blank Excel Cells Copied From Database”
Category: Excel VBA
Automatically Add Sheet When Excel Opens
On the Contextures YouTube channel, someone asked if Excel can automatically create a sheet when the file opens:
- “this question from my friend, she always need to open same file and create a new sheet with the name of the month when her is updating the data. is there any ways to skip the above process?”
Video Answer
Since the question came from YouTube, I provided the answer in a video, which you can see at the end of this blog post.
If you prefer to see the code, or download a sample file, you can find the details below.
How the Add Sheet Code Works
The goal is to add a worksheet with the month name, when the Excel file opens. We only want that to happen at the start of the month, if the sheet doesn’t exist already.
We’ll write a macro that:
- figures out what the current month is
- checks for a sheet with that name
- adds that sheet, if it doesn’t exist
The Add Worksheet Code
Insert a regular module in the workbook, and paste in the following code. I used yyyy-mm as the sheet name format, but you could use a different format.
For example, to see the full month name, use mmmm as the format.
Sub AddMonthWkst() Dim ws As Worksheet Dim strName As String Dim bCheck As Boolean On Error Resume Next strName = Format(Date, "yyyy_mm") bCheck = Len(Sheets(strName).Name) > 0 If bCheck = False Then Set ws = Worksheets.Add(Before:=Sheets(1)) ws.Name = strName End If End Sub
Run the Code Automatically
To make the code run automatically, when the workbook opens, you’ll create a Workbook_Open event.
Paste the following code on the ThisWorksheet module:
Private Sub Workbook_Open()
AddMonthWkst
End Sub
Download the Sample File
To see the workbook and the Add Worksheet code, you can download the Add Worksheet sample file.
The file is in Excel 2007 format, and zipped. It contains macros, so you’ll need to enable them, to see the code working.
Watch the Add Worksheet Automatically Video
To see the steps for creating the code, and making it run automatically, you can watch this Excel Video Tutorial.
_____________
Fix Those Wandering Excel Comments
Do you ever open an Excel workbook, and find that tragedy has struck your comments? You spent hours inserting those comments, and making them just the right size and shape. Then, for no apparent reason, everything changes. Comments are in the wrong place, and wrong size. Here’s how to fix those wandering Excel comments.
Continue reading “Fix Those Wandering Excel Comments”
Excel Bingo Card Random Number Code
A couple of years ago, I posted about an Excel bingo workbook, that you could use to create a set of three cards with random numbers.
Bingo Card Formulas
In the Excel workbook, the bingo card sheet uses the INDEX and MATCH functions to pull the numbers from another sheet.
- =INDEX(Numbers!$M$1:$M$15, MATCH(LARGE(
Numbers!$N$1:$N$15, ROW()-1), Numbers!$N$1:$N$15,0))

There were a few follow up workbooks, including an Excel Bingo Number Selector file from Dick Kusleika.
Horizontal Number Lists
This week, Carrie posted a comment on that article, and she wanted to adapt the bingo cards so they could be printed with Adobe InDesign. Instead of a square with 25 numbers, that program needs the 25 numbers in a single row.
Using the example in the screen shot above, the numbers in the first two rows would be arranged like this, followed by the numbers from the remaining rows:

Random Number Code
Jim Cone pitched in, and wrote some code to generate the random numbers in single rows, but it created some duplicates in the rows. Carrie didn’t want an uprising in the bingo hall, so we sent Jim away to try again. 😉
It didn’t take long for him to return with some code that worked correctly, so Carrie, and her Hummel figurine collecting friends, can safely play bingo this summer.
Whew! A bit later, Dick posted an update for Jim’s code. It’s shorter, and does the job very well.
Copy the Random Number Code
Thanks Jim and Dick! I’m sure Carrie appreciates the code, and maybe it will help a few other people.
To use this random number code, copy it to a regular code module in your workbook.
Then, go to a blank sheet, and run the SurelyYouCantBeSerious_R1 code.
Sub SurelyYouCantBeSerious_R1() 'Generates 800 sets of random Bingo numbers with no duplicates. 'Each row contains an individual set of Bingo numbers. 'Designed to be used with the "Adobe InDesign" application. 'Jim Cone - Portland, Oregon USA - February 02, 2011 '[email protected] - remove all "X" 'Edited by Dick dailydoseofexcel.com On Error GoTo DontCallMeShirley Dim arrList(1 To 800, 1 To 25) As Long Dim j As Long Dim R As Long 'B COLUMNS '1 to 15 in the B column Randomize For R = 1 To 800 For j = 1 To 5 FillList arrList, j, R Next j Next R Range("A1:Y800").Value = arrList() Exit Sub DontCallMeShirley: Beep Resume Next End Sub '========== Sub FillList(ByRef arrList As Variant, lStart As Long, R As Long) Dim j As Long Dim C As Long Dim N As Long Dim arrCheck(1 To 75) As Long j = 1 For C = lStart To 25 Step 5 Do While j < 6 'Int((High - Low + 1) * Rnd + Low) N = Int(Rnd * 15 + ((lStart - 1) * 15 + 1)) If arrCheck(N) < 1 Then arrList(R, C) = N arrCheck(N) = N j = j + 1 Exit Do End If Loop Next C End Sub
______________
Excel AutoFilter With Criteria in a Range
In Excel 2003, and earlier versions, an AutoFilter allows only two criteria for each column. In Excel 2007 and later, you can select multiple criteria from each column in the table. See how to apply an Excel AutoFilter with multiple criteria in a range on the worksheet.
Update: Get the latest version of this workbook on my Contextures site: Filter Criteria List Macro.
Continue reading “Excel AutoFilter With Criteria in a Range”
Add List Box to Excel Worksheet
In some workbooks, you want users to select one or more from a list of options.
Select Items in a List Box
To make it easier for people to enter data, you can add a List Box, with check boxes, to an Excel worksheet.

List Box on Data Entry Sheet
You wouldn’t want to have too many List Boxes on a worksheet, but it would be handy in a data entry form, like this one.
- Tip: In worksheets where you need several cells with multiple options, you could use my technique for selecting multiple items from a data validation drop down.

Set Up a List Box
On the Contextures website, there are instructions for setting up a List Box, and a sample workbook.
You can enter records, one at a time, on the data entry sheet, and run the macro to store the saved records another sheet.
Store Selected Items
The List Box macro code pulls the selected items from the List Box, and stores them in separate cells.

Watch the List Box Video
To see the steps for creating a List Box on a worksheet, you can watch this short Excel video tutorial.
____________
Excel VBA Click Shape to Sort Column
People are lazy! Shocking, I know, but who wants to click twice in Excel, if you can do the same thing by only clicking once?

Click to Sort Column
Peterson, champion of weary Excel users, created this sample Excel VBA sort code, that adds invisible rectangles at the top of each column in a table.
A macro is automatically assigned to each rectangle, and it sorts the table by that column, when you click it.
Benefits of Sort Macros
Here are two benefits of using Dave’s code:
- Reduced wear and tear on clicking fingers
- Less risk of table scrambling, because it ensures the entire table is selected before sorting

Edit the Setup Macro
There are two macros in Dave’s sample file.
- SetupOneTime – run this once, to add the hidden rectangles
- SortTable – sorts table by selected column, when heading is clicked
Before you run the SetupOneTime macro, you should edit both macros, to adjust them for your workbook
- On the Excel Ribbon, click the Developer tab, then click Macros
- Click SetupOneTime, and click Edit

The Setup Macro Code
In the SetupOneTime macro, change the iCol variable to match the number of columns in your table. If your table doesn’t start in cell A1, change that reference.

Edit the SortTable Macro
Next, change the variables in the SortTable macro, to suit your table settings. You can adjust:
- TopRow (row where headings are located)
- iCol (number of columns in the table)
- strCol (column to check for last row)

If you want to see the rectangle outlines, change the Line.Visible setting to True.

Run the SetupOneTime Macro
After you’ve edited the macros, you can run the setup macro:
- Select the sheet where your table is located.
- On the Excel Ribbon, click the Developer tab, then click Macros
- Click SetupOneTime, and click Run

Now, click a heading in the table, to sort by that column.
Excel 2007 Shapes Problem
When I was getting this blog post ready, I discovered that Dave’s original code needed a tweak before it would work correctly in Excel 2007 and Excel 2010.
In the original code, written for Excel 2003, there was one line of code that made the rectangular shape invisible:
.Fill.Visible = False
In the newer versions of Excel, only the borders of the invisible shapes were clickable, so I had to change the code to these two lines:
.Fill.Solid .Fill.Transparency = 1#
The revised code worked for me in Excel 2003, 2007 and 2010, creating transparent shapes that were clickable.

Download the Sample Workbook
To see the full code for the SetupOneTime and SortTable macros, and download the sample workbook, visit the Sort Data With Excel Macros page on the Contextures website.
And for more Excel advanced sorting tips, go to the Excel Add-in Advanced Sorting page on my Contextures site.
Watch the Click Headings to Sort Columns Video
To see the steps for editing the code, adding the rectangles, and clicking the hidden shapes, you can watch this short Excel tutorial video.
_________________
Get Details in Excel VBA Code
Did you ever get an Excel file from someone else, and try to sort out their Excel VBA code? Or, even worse, open an Excel file that you wrote long ago, and try to remember what all those variables mean?
I spend lots of time staring at Excel code, but apparently I don’t use the right-click menu too often, because I hadn’t noticed a couple of handy commands until recently.
These commands can help you decipher that mysterious code, and unravel the complicated sections.
Excel VBA Quick Info
The first handy command is Quick Info. I have Auto Quick Info turned on in the VBE Editor options, and it helps me remember the syntax as I type the code.

Right-Click for Quick Info
What I didn’t realize was that you can right-click on a variable, function, statement, method, or procedure in the code, and click Quick Info.

A tooltip appears, with details on the selected item.

Excel VBA Definition
The other right-click command that I finally discovered is the Definition command.
Click the Definition command, and it takes you to the selected variable’s definition.
Finding the definition is easy in most procedures, but in a long procedure, with a long list of variables, the Definition command really makes the job easier.
It’s especially helpful if the variable is defined on a different code module!

___________
Excel Error – Selection Is Too Large
To fill blank cells, or delete rows with blanks cells, you can use Excel’s Go To Special feature.

For example, in the worksheet shown below, you might want to fill in all the blanks in column B, by copying the value from the row above.

There are instructions on the Contextures website to fill blank cells, by using Go To Special to select the blanks.
You can do this manually, and there’s sample code to make the job easier.
Selection Is Too Large Error
This technique works very well, unless you’re trying to fill blank cells in a long list. In that case, you might see the error message, “Selection is too large.”

This happens in Excel 2007, and earlier versions, because there is a limit of 8192 separate areas that the special cells feature can handle. (This problem has been fixed in Excel 2010.)
There are details on Ron de Bruin’s website: SpecialCells Limit Problem.
Work in Smaller Chunks
If you run into this error, you can work with smaller chunks of data instead.
- If you’re making the changes manually, select a few thousand rows, instead of the full column.
- If you’re using a macro, you can loop through the cells in large chunks, e.g. 8000 rows, instead of trying to change the entire column.
On the Contextures website, Fill Blank Cells Macro – Example 3 checks for the number of areas, using Ron’s sample code, and uses a loop if necessary.
The code is shown below, and it shows a message box if the range is over the special cells limit. You can remove that line — it’s just there for information.
Sub FillColBlanks()
'https://www.contextures.com/xlDataEntry02.html
'by Dave Peterson 2004-01-06
'fill blank cells in column with value above
'2010-10-12 incorporated Ron de Bruin's test for special cells limit
'https://www.rondebruin.nl/specialcells.htm
Dim wks As Worksheet
Dim rng As Range
Dim rng2 As Range
Dim LastRow As Long
Dim col As Long
Dim lRows As Long
Dim lLimit As Long
Dim lCount As Long
On Error Resume Next
lRows = 2 'starting row
lLimit = 8000
Set wks = ActiveSheet
With wks
col = ActiveCell.Column
'try to reset the lastcell
Set rng = .UsedRange
LastRow = .Cells. _
SpecialCells(xlCellTypeLastCell).Row
Set rng = Nothing
lCount = .Columns(col) _
.SpecialCells(xlCellTypeBlanks) _
.Areas(1).Cells.Count
If lCount = 0 Then
MsgBox "No blanks found in selected column"
Exit Sub
ElseIf lCount = .Columns(col).Cells.Count Then
'this line can be deleted
MsgBox "Over the Special Cells Limit"
Do While lRows < LastRow
Set rng = .Range(.Cells(lRows, col), _
.Cells(lRows + lLimit, col)) _
.Cells.SpecialCells(xlCellTypeBlanks)
rng.FormulaR1C1 = "=R[-1]C"
lRows = lRows + lLimit
Loop
Else
Set rng = .Range(.Cells(2, col), _
.Cells(LastRow, col)) _
.Cells.SpecialCells(xlCellTypeBlanks)
rng.FormulaR1C1 = "=R[-1]C"
End If
'replace formulas with values
With .Cells(1, col).EntireColumn
.Value = .Value
End With
End With
End Sub
_______________
Excel VBA – Macro Runs When Worksheet Changed
Are you ready for Spreadsheet Day on October 17th?
Maybe you can add a Spreadsheet Day message to all your workbooks, using the technique described in this blog post.
It’s a macro that runs every time the worksheet changed. I’m sure your co-workers would enjoy that!
Continue reading “Excel VBA – Macro Runs When Worksheet Changed”