Extract cell references populated with values [VBA]
This article demonstrates a macro that returns cell references for cell ranges populated with values on a worksheet.
I have to combine 200 columns into one list. I know. I tried steps from 'Combine cell ranges into a single range while eliminating blanks' UDF, but looks like typing the formula itself is going to be a big deal. Any advice?
(To give a bit of a background, I am trying to compare 200 columns to one column of data and figured it would be easier if I combine all 200 into one column and then compare, it would be easy).
What you will learn in this article
- Create a macro that extracts cell references of populated cells in a worksheet.
- Save the answer from an inputbox to a variable.
- Loop through populated cells in a column.
- How to use the currentregion property with an object reference.
- Iterate through worksheet columns.
- Append values to a variable.
- Add values to a collection variable.
- Insert a new worksheet and save an object reference to a variable.
- Save the result to a given cell.
The following macro moves from column to column and checks for values. If a value is found, the current region property (Ctrl + A) is applied and the cell range address is saved. A new sheet is created and all unique distinct cell references are concatenated using a delimiting character into cell A1.
The current region is a range bounded by any combination of blank rows and blank columns. In other words, the macro creates cell references to all cell ranges populated with values.
VBA Code
'Name macro Sub ExtractAddresses() 'Dimension variables and declare data types Dim sht As Worksheet Dim CurCell As Range Dim Adr As New Collection Dim c As Single Dim Value As Variant Dim result As String, delch As String 'Show inputbox and ask for a delimiting character, save to variable delch delch = InputBox("Delimiting character:") 'The SET statement allows you to save an object reference to a variable Set CurCell = ActiveSheet.Range("A1") 'Iterate from 1 to the number of columns in your workbook using the FOR NEXT statement For c = 1 To Columns.Count - 1 'The SET statement allows you to save an object reference to a variable, in this case it is next populated cell in column A. It returns the last cell if column A has no populated cells. Set CurCell = CurCell.End(xlDown) 'Loop through following lines as long as cell saved to CurCell is not empty. Do While CurCell.Value <> "" 'Check if the length of the address of object CurCell with currentregion property is larger than 0 (zero) If Len(CurCell.CurrentRegion.Address) > 0 Then 'Enable error handling, an error occurs if a cell reference already exists in the collection variable On Error Resume Next 'Save address of currentregion property based on object CurCell to collection variable Adr Adr.Add CurCell.CurrentRegion.Address, CStr(CurCell.CurrentRegion.Address) 'Disable error handling On Error GoTo 0 End If 'Check if the CurCell row number equals the last row number in workbbok, if so stop Loop If CurCell.Row = Rows.Count Then Exit Do 'The SET statement allows you to save an object reference to a variable, in this case it is the last cell in column A. Set CurCell = CurCell.End(xlDown) Loop 'Save an object reference to the next cell to the right based on variable c to variable CurCell Set CurCell = Range("A1").Offset(0, c) 'Continue with next number Next c 'Iterate through each value saved in collection variable Adr For Each Value In Adr 'Add value to string variable result using variable delch as a delimiting character result = result & delch & Value 'Continue with next value in collection Next Value 'Add a new sheet and save a reference to variable sht Set sht = Sheets.Add 'Save text in string result to cell A1 sht.Range("A1") = Right(result, Len(result) - 1) End Sub
Where to put the code?
- Copy above VBA code.
- Press Alt + F11 to open the Visual Basic Editor.
- Select your workbook in the Project Explorer.
- Press with left mouse button on "Insert" on the menu.
- Press with left mouse button on "Module" to create a code module named Module1 that will be displayed below "Modules" in the Project Explorer.
- Paste VBA code to the code window, see image above.
- Return to Excel.
Note, save your workbook with file extension *.xlsm (macro-enabled) to attach the VBA code to the workbook.
How to use the macro
The animated image above shows how to run the macro.
- Press Alt + F8 to open the macro dialog box.
- Select ExtractAddresses.
- Press with mouse on button "Run".
- The macro asks for a delimiting character.
- The macro creates a new worksheet and populates cell A1 with cell references containing values. These cell references have a comma as a delimiting character.
Macro category
This article demonstrates how to add or remove a value in a regular drop down list based on a list […]
In this tutorial I am going to show you how to add values to drop down list in cell C2. This […]
This article demonstrates how to place values automatically to a table based on two conditions using a short macro. Cell […]
This tutorial shows you how to add a record to a particular worksheet based on a condition, the image above […]
This article demonstrates how to automatically create drop-down lists if adjacent data grows, there are two methods explained here. The […]
Excel does not resize columns as you type by default as the image above demonstrates. You can easily resize all […]
This article demonstrates how to automatically enter data in cells if an adjacent cell is populated using VBA code. In […]
In this small tutorial, I am going to show you how to create basic data entry with a small amount […]
Here is my contribution to all excel calendars out there. My calendar is created in Excel 2007 and uses both […]
In this article I will demonstrate how to quickly change chart data range utilizing a combobox (drop-down list). The above […]
The image above shows a chart populated with data from an Excel defined Table. The worksheet contains event code that […]
What's on this page Press with left mouse button on a specific cell to hide/show entire column Where to put […]
Question: I have multiple worksheets in a workbook. Each worksheets is project specific. Each worksheet contains almost identical format. The […]
In this blog post, I will demonstrate some VBA copying techniques that may be useful if you don't know the […]
I will in this article demonstrate a macro that automatically opens all workbooks in a folder and subfolders, one by […]
I will in this article demonstrate a macro that copies criteria from one Excel Table and applies them to another […]
This article demonstrates several VBA macros, they will save you time if you have lots of worksheets. The first macro […]
I will in this article demonstrate a macro that counts how many times a specific text string is found in […]
This article describes how to create a button and place it on an Excel worksheet then assign a macro to […]
Question: hi all, thanks for the great formula/array formula. it works great. lately, i noticed that the array formula will […]
It can sometimes be helpful having a large cell value in a comment. You can then easily hover over cell […]
This article demonstrates a macro that inserts new worksheets based on names in a cell range. The cell range may […]
Save links to your favorite macros in a personal tab on the ribbon for easy access and become more productive. […]
In a previos post:Excel vba: Save invoice data we added/copied data between sheets. This post describes how to overwrite existing […]
This workbook contains two worksheets, one worksheet shows a calendar and the other worksheet is used to store events. The […]
In this article, I am going to demonstrate a simple workbook where you can create or delete projects and add […]
In this post I am going to demonstrate how to quickly apply a filter to a table. I am using […]
In this tutorial, I am going to demonstrate how to filter an Excel define Table through a VBA macro. How it […]
This article describes different ways to locate literal or hardcoded values in formulas. The image above shows the result from […]
This post Find the longest/smallest consecutive sequence of a value has a few really big array formulas. Today I would like to […]
This article describes a macro that hides specific columns automatically based on values in two given cells. I am also […]
This article demonstrates techniques to hide and unhide worksheets programmatically. The image above shows the Excel window and the worksheet […]
This article demonstrates event code combined with Conditional Formatting that highlights overlapping date ranges based on the selected date range. […]
This post describes how to add a new custom-built item to the shortcut menu in Excel, when you press with right […]
The Quick Access Toolbar is located at the very top of your Excel window, I highly recommend that you place your […]
Rahul asks: I want to know how to create a vlookup sheet, and when we enter a name in a […]
This article demonstrates a formula and a VBA macro that returns every n-th row from a given cell range. The […]
The image above demonstrates a macro linked to a button. Press with left mouse button on the button and the […]
If you try to copy multiple cell ranges on a worksheet that don't have the same number of rows or […]
Did you know that you can select all cells containing comments in the current sheet? Press F5, press with left […]
This article describes how to create an interactive chart, the user may press with left mouse button on a button […]
Today I would like to share with you these small event handler procedures that make it easier for you to […]
This article demonstrates how to automatically create log entries when a workbook opens or closes using event code. Column A […]
In this smaller example, column D (Category) has empty cells, shown in the picture above. If your column contains thousands of […]
Macros and custom functions are great, they can automate many tedious tasks. To have them available whenever you need them, […]
This article demonstrates macros that save worksheets to a single pdf file. What's on this webpage Export all worksheets in […]
A dialog box is an excellent alternative to a userform, they are built-in to VBA and can save you time […]
This article demonstrates how to insert and use a scroll bar (Form Control) in Excel. It allows the user to […]
The image above shows an array formula in cell D6 that extracts missing numbers i cell range B3:B7, the lower […]
In this post, I am going to demonstrate how to automatically create a new sheet in the current workbook and […]
The following macro inserts a new sheet to your workbook and lists all Excel defined Tables and corresponding Table headers […]
This article demonstrates how to locate a shape in Excel programmatically based on the value stored in the shape. The […]
This article demonstrates how to move a shape, a black arrow in this case, however, you can use whatever shape […]
This article demonstrates a User Defined Function (UDF) that multiplies numbers in each row with the remaining rows in a […]
To be able to use a Pivot Table the source data you have must be arranged in way that a […]
This tutorial shows you how to list excel files in a specific folder and create adjacent checkboxes, using VBA. The […]
This article explains how to set up a workbook so a macro is run every time you open the workbook. […]
In this tutorial I am going to explain how to: Create a combo box (form control) Filter unique values and […]
In this post I am going to demonstrate two things: How to populate a combobox based on column headers from […]
Excel defined Tables, introduced in Excel 2007, sort, filter and organize data any way you like. You can also format […]
This post demonstrates how to: Insert a button to your worksheet Assign a macro to the button Create a basic […]
This article demonstrates a macro that allows you to rearrange and distribute concatenated values across multiple rows in order to […]
In this post I am going to rearrange values from a list into unique columns. Before: After: The code Get […]
This article demonstrates how to run a VBA macro using a Drop Down list. The Drop Down list contains two […]
This article demonstrates a macro that copies values between sheets. I am using the invoice template workbook. This macro copies […]
This article demonstrates a macro that automatically applies a filter to an Excel defined Table based on the result from […]
This post demonstrates how to view saved invoices based on the invoice number using a userform. The userform appears when the […]
This post demonstrates a macro that automatically selects cell A1 on each sheet right before you close a workbook. The […]
This article explains how to hide a specific image in Excel using a shape as a button. If the user […]
This article demonstrates a macro and a formula that allows you to sort delimited data in a cell or cell […]
This article demonstrates how to sort a specific column in an Excel defined Table based on event code. The event […]
In this post I am going to show how to create a new sheet for each airplane using vba. The […]
This article demonstrates how the user can run a macro by press with left mouse button oning on a button, […]
This blog post describes how to insert qualifers to make "text to columns" conversion easier. Example I copied a table from […]
This blog post demonstrates how to create, populate and change comboboxes (form control) programmatically. Form controls are not as flexible […]
What's on this page Copy a file Copy and rename a file Rename a file List files in a folder […]
There are two different kinds of text boxes, Form controls and ActiveX Controls. Form controls can only be used on […]
Excel categories
3 Responses to “Extract cell references populated with values [VBA]”
Leave a Reply
How to comment
How to add a formula to your comment
<code>Insert your formula here.</code>
Convert less than and larger than signs
Use html character entities instead of less than and larger than signs.
< becomes < and > becomes >
How to add VBA code to your comment
[vb 1="vbnet" language=","]
Put your VBA code here.
[/vb]
How to add a picture to your comment:
Upload picture to postimage.org or imgur
Paste image link to your comment.
If you do not mind the addresses for the ranges being presented in a different order, then this slightly shorter macro (which uses a completely different underlying method of obtaining the addresses) should also work...
One comment about your code. I changed the range C17:C21 to formulas (=F10 copied down) and your code worked fine. Then I forced C17 to return a #REF error (put =F1 in a cell, copied it up one cell to produce the error, and then copied that error cell to C17 and then ran your code again. Your code no longer reported the addresses for C17:C21. That is not the strange part, though (I think your Do statement may be filtering it out)... when I corrected the error by copying C18 up one cell to replace the error cell with a valid formula, your code still did not see the range C17:C21. Even after I used PasteSpecial to turn the formulas back to constants, your code still refused to see the range C17:C21. It is as though once the error was introduced to the range, your code somehow still "saw" the original error on subsequent runs even though it was no longer there! I have no explanation as to why that should be happening.
Just to mention, my code above has no problem with cells containing errors. Also, to make things easier to read, I set my code up to report relative addresses (that is, addresses without the $ signs).
One comment about your code. I changed the range C17:C21 to formulas (=F10 copied down) and your code worked fine. Then I forced C17 to return a #REF error (put =F1 in a cell, copied it up one cell to produce the error, and then copied that error cell to C17 and then ran your code again. Your code no longer reported the addresses for C17:C21. That is not the strange part, though (I think your Do statement may be filtering it out)... when I corrected the error by copying C18 up one cell to replace the error cell with a valid formula, your code still did not see the range C17:C21. Even after I used PasteSpecial to turn the formulas back to constants, your code still refused to see the range C17:C21. It is as though once the error was introduced to the range, your code somehow still "saw" the original error on subsequent runs even though it was no longer there! I have no explanation as to why that should be happening.
That is weird, I get a "Run-time error '13' Type missmatch error" (Excel 2010)
Do While CurCell.Value <> ""
Just to mention, my code above has no problem with cells containing errors. Also, to make things easier to read, I set my code up to report relative addresses (that is, addresses without the $ signs).
That is great, it is incredibly fast too! Really interesting approach.
This line is interesting:
Mid(Addresses, Len(Delimiter) + 1)
If you enter the Mid function in a worksheet, you can´t skip the num_chars argument. At least you need to type a comma.
Mid(text, start_num, num_chars)
becomes
Mid(text, start_num,)
But it always returns a blank cell. That is not the case when used in a macro.
[…] I have reused some parts of Rick Rothstein´s macro. […]