“It is a capital mistake to theorize before one has data”- Sir Arthur Conan Doyle
This post covers everything you need to know about using Cells and Ranges in VBA. You can read it from start to finish as it is laid out in a logical order. If you prefer you can use the table of contents below to go to a section of your choice.
Topics covered include Offset property, reading values between cells, reading values to arrays and formatting cells.
Contents
- 1 A Quick Guide to Ranges and Cells
- 2 Download the Code
- 3 The Webinar
- 4 Introduction
- 5 Important Notes
- 6 The Range Property
- 7 The Cells Property of the Worksheet
- 8 Using Cells and Range together
- 9 The Offset Property of Range
- 10 Using the Range CurrentRegion
- 11 Using Rows and Columns as Ranges
- 12 Using Range in place of Worksheet
- 13 Reading Values from one Cell to another
- 14 Using the Range.Resize Method
- 15 Reading Values to variables
- 16 How to Copy and Paste Cells
- 17 Reading a Range of Cells to an Array
- 18 Going through all the cells in a Range
- 19 Formatting Cells
- 20 Main Points
- 21 What’s Next?
A Quick Guide to Ranges and Cells
Function | Takes | Returns | Example | Gives |
---|---|---|---|---|
Range | cell address | multiple cells | .Range("A1:A4") | $A$1:$A$4 |
Cells | row, column | one cell | .Cells(1,5) | $E$1 |
Offset | row, column | multiple cells | Range("A1:A2") .Offset(1,2) | $C$2:$C$3 |
Rows | row(s) | one or more rows | .Rows(4) .Rows("2:4") | $4:$4 $2:$4 |
Columns | column(s) | one or more columns | .Columns(4) .Columns("B:D") | $D:$D $B:$D |
Download the Code
The Webinar
If you are a member of the VBA Vault, then click on the image below to access the webinar and the associated source code.
(Note: Website members have access to the full webinar archive.)
Introduction
This is the third post dealing with the three main elements of VBA. These three elements are the Workbooks, Worksheets and Ranges/Cells. Cells are by far the most important part of Excel. Almost everything you do in Excel starts and ends with Cells.
Generally speaking, you do three main things with Cells
- Read from a cell.
- Write to a cell.
- Change the format of a cell.
Excel has a number of methods for accessing cells such as Range, Cells and Offset.These can cause confusion as they do similar things and can lead to confusion
In this post I will tackle each one, explain why you need it and when you should use it.
Let’s start with the simplest method of accessing cells – using the Range property of the worksheet.
Important Notes
I have recently updated this article so that is uses Value2.
You may be wondering what is the difference between Value, Value2 and the default:
' Value2 Range("A1").Value2 = 56 ' Value Range("A1").Value = 56 ' Default uses value Range("A1") = 56
Using Value may truncate number if the cell is formatted as currency. If you don’t use any property then the default is Value.
It is better to use Value2 as it will always return the actual cell value(see this article from Charle Williams.)
The Range Property
The worksheet has a Range property which you can use to access cells in VBA. The Range property takes the same argument that most Excel Worksheet functions take e.g. “A1”, “A3:C6” etc.
The following example shows you how to place a value in a cell using the Range property.
' https://excelmacromastery.com/ Public Sub WriteToCell() ' Write number to cell A1 in sheet1 of this workbook ThisWorkbook.Worksheets("Sheet1").Range("A1").Value2 = 67 ' Write text to cell A2 in sheet1 of this workbook ThisWorkbook.Worksheets("Sheet1").Range("A2").Value2 = "John Smith" ' Write date to cell A3 in sheet1 of this workbook ThisWorkbook.Worksheets("Sheet1").Range("A3").Value2 = #11/21/2017# End Sub
As you can see Range is a member of the worksheet which in turn is a member of the Workbook. This follows the same hierarchy as in Excel so should be easy to understand. To do something with Range you must first specify the workbook and worksheet it belongs to.
For the rest of this post I will use the code name to reference the worksheet.
The following code shows the above example using the code name of the worksheet i.e. Sheet1 instead of ThisWorkbook.Worksheets(“Sheet1”).
' https://excelmacromastery.com/ Public Sub UsingCodeName() ' Write number to cell A1 in sheet1 of this workbook Sheet1.Range("A1").Value2 = 67 ' Write text to cell A2 in sheet1 of this workbook Sheet1.Range("A2").Value2 = "John Smith" ' Write date to cell A3 in sheet1 of this workbook Sheet1.Range("A3").Value2 = #11/21/2017# End Sub
You can also write to multiple cells using the Range property
' https://excelmacromastery.com/ Public Sub WriteToMulti() ' Write number to a range of cells Sheet1.Range("A1:A10").Value2 = 67 ' Write text to multiple ranges of cells Sheet1.Range("B2:B5,B7:B9").Value2 = "John Smith" End Sub
You can download working examples of all the code from this post from the top of this article.
The Cells Property of the Worksheet
The worksheet object has another property called Cells which is very similar to range. There are two differences
- Cells returns a range of one cell only.
- Cells takes row and column as arguments.
The example below shows you how to write values to cells using both the Range and Cells property
' https://excelmacromastery.com/ Public Sub UsingCells() ' Write to A1 Sheet1.Range("A1").Value2 = 10 Sheet1.Cells(1, 1).Value2 = 10 ' Write to A10 Sheet1.Range("A10").Value2 = 10 Sheet1.Cells(10, 1).Value2 = 10 ' Write to E1 Sheet1.Range("E1").Value2 = 10 Sheet1.Cells(1, 5).Value2 = 10 End Sub
You may be wondering when you should use Cells and when you should use Range. Using Range is useful for accessing the same cells each time the Macro runs.
For example, if you were using a Macro to calculate a total and write it to cell A10 every time then Range would be suitable for this task.
Using the Cells property is useful if you are accessing a cell based on a number that may vary. It is easier to explain this with an example.
In the following code, we ask the user to specify the column number. Using Cells gives us the flexibility to use a variable number for the column.
' https://excelmacromastery.com/ Public Sub WriteToColumn() Dim UserCol As Integer ' Get the column number from the user UserCol = Application.InputBox(" Please enter the column...", Type:=1) ' Write text to user selected column Sheet1.Cells(1, UserCol).Value2 = "John Smith" End Sub
In the above example, we are using a number for the column rather than a letter.
To use Range here would require us to convert these values to the letter/number cell reference e.g. “C1”. Using the Cells property allows us to provide a row and a column number to access a cell.
Sometimes you may want to return more than one cell using row and column numbers. The next section shows you how to do this.
Using Cells and Range together
As you have seen you can only access one cell using the Cells property. If you want to return a range of cells then you can use Cells with Ranges as follows
' https://excelmacromastery.com/ Public Sub UsingCellsWithRange() With Sheet1 ' Write 5 to Range A1:A10 using Cells property .Range(.Cells(1, 1), .Cells(10, 1)).Value2 = 5 ' Format Range B1:Z1 to be bold .Range(.Cells(1, 2), .Cells(1, 26)).Font.Bold = True End With End Sub
As you can see, you provide the start and end cell of the Range. Sometimes it can be tricky to see which range you are dealing with when the value are all numbers. Range has a property called Address which displays the letter/ number cell reference of any range. This can come in very handy when you are debugging or writing code for the first time.
In the following example we print out the address of the ranges we are using:
' https://excelmacromastery.com/ Public Sub ShowRangeAddress() ' Note: Using underscore allows you to split up lines of code With Sheet1 ' Write 5 to Range A1:A10 using Cells property .Range(.Cells(1, 1), .Cells(10, 1)).Value2 = 5 Debug.Print "First address is : " _ + .Range(.Cells(1, 1), .Cells(10, 1)).Address ' Format Range B1:Z1 to be bold .Range(.Cells(1, 2), .Cells(1, 26)).Font.Bold = True Debug.Print "Second address is : " _ + .Range(.Cells(1, 2), .Cells(1, 26)).Address End With End Sub
In the example I used Debug.Print to print to the Immediate Window. To view this window select View->Immediate Window(or Ctrl G)
You can download all the code for this post from the top of this article.
The Offset Property of Range
Range has a property called Offset. The term Offset refers to a count from the original position. It is used a lot in certain areas of programming. With the Offset property you can get a Range of cells the same size and a certain distance from the current range. The reason this is useful is that sometimes you may want to select a Range based on a certain condition. For example in the screenshot below there is a column for each day of the week. Given the day number(i.e. Monday=1, Tuesday=2 etc.) we need to write the value to the correct column.
We will first attempt to do this without using Offset.
' https://excelmacromastery.com/ ' This sub tests with different values Public Sub TestSelect() ' Monday SetValueSelect 1, 111.21 ' Wednesday SetValueSelect 3, 456.99 ' Friday SetValueSelect 5, 432.25 ' Sunday SetValueSelect 7, 710.17 End Sub ' Writes the value to a column based on the day Public Sub SetValueSelect(lDay As Long, lValue As Currency) Select Case lDay Case 1: Sheet1.Range("H3").Value2 = lValue Case 2: Sheet1.Range("I3").Value2 = lValue Case 3: Sheet1.Range("J3").Value2 = lValue Case 4: Sheet1.Range("K3").Value2 = lValue Case 5: Sheet1.Range("L3").Value2 = lValue Case 6: Sheet1.Range("M3").Value2 = lValue Case 7: Sheet1.Range("N3").Value2 = lValue End Select End Sub
As you can see in the example, we need to add a line for each possible option. This is not an ideal situation. Using the Offset Property provides a much cleaner solution
' https://excelmacromastery.com/ ' This sub tests with different values Public Sub TestOffset() DayOffSet 1, 111.01 DayOffSet 3, 456.99 DayOffSet 5, 432.25 DayOffSet 7, 710.17 End Sub Public Sub DayOffSet(lDay As Long, lValue As Currency) ' We use the day value with offset specify the correct column Sheet1.Range("G3").Offset(, lDay).Value2 = lValue End Sub
As you can see this solution is much better. If the number of days in increased then we do not need to add any more code. For Offset to be useful there needs to be some kind of relationship between the positions of the cells. If the Day columns in the above example were random then we could not use Offset. We would have to use the first solution.
One thing to keep in mind is that Offset retains the size of the range. So .Range(“A1:A3”).Offset(1,1) returns the range B2:B4. Below are some more examples of using Offset
' https://excelmacromastery.com/ Public Sub UsingOffset() ' Write to B2 - no offset Sheet1.Range("B2").Offset().Value2 = "Cell B2" ' Write to C2 - 1 column to the right Sheet1.Range("B2").Offset(, 1).Value2 = "Cell C2" ' Write to B3 - 1 row down Sheet1.Range("B2").Offset(1).Value2 = "Cell B3" ' Write to C3 - 1 column right and 1 row down Sheet1.Range("B2").Offset(1, 1).Value2 = "Cell C3" ' Write to A1 - 1 column left and 1 row up Sheet1.Range("B2").Offset(-1, -1).Value2 = "Cell A1" ' Write to range E3:G13 - 1 column right and 1 row down Sheet1.Range("D2:F12").Offset(1, 1).Value2 = "Cells E3:G13" End Sub
Using the Range CurrentRegion
CurrentRegion returns a range of all the adjacent cells to the given range.
In the screenshot below you can see the two current regions. I have added borders to make the current regions clear.
A row or column of blank cells signifies the end of a current region.
You can manually check the CurrentRegion in Excel by selecting a range and pressing Ctrl + Shift + *.
If we take any range of cells within the border and apply CurrentRegion, we will get back the range of cells in the entire area.
For example
Range(“B3”).CurrentRegion will return the range B3:D14
Range(“D14”).CurrentRegion will return the range B3:D14
Range(“C8:C9”).CurrentRegion will return the range B3:D14
and so on
How to Use
We get the CurrentRegion as follows
' Current region will return B3:D14 from above example Dim rg As Range Set rg = Sheet1.Range("B3").CurrentRegion
Read Data Rows Only
Read through the range from the second row i.e.skipping the header row
' Current region will return B3:D14 from above example Dim rg As Range Set rg = Sheet1.Range("B3").CurrentRegion ' Start at row 2 - row after header Dim i As Long For i = 2 To rg.Rows.Count ' current row, column 1 of range Debug.Print rg.Cells(i, 1).Value2 Next i
Remove Header
Remove header row(i.e. first row) from the range. For example if range is A1:D4 this will return A2:D4
' Current region will return B3:D14 from above example Dim rg As Range Set rg = Sheet1.Range("B3").CurrentRegion ' Remove Header Set rg = rg.Resize(rg.Rows.Count - 1).Offset(1) ' Start at row 1 as no header row Dim i As Long For i = 1 To rg.Rows.Count ' current row, column 1 of range Debug.Print rg.Cells(i, 1).Value2 Next i
Using Rows and Columns as Ranges
If you want to do something with an entire Row or Column you can use the Rows or Columns property of the Worksheet. They both take one parameter which is the row or column number you wish to access
' https://excelmacromastery.com/ Public Sub UseRowAndColumns() ' Set the font size of column B to 9 Sheet1.Columns(2).Font.Size = 9 ' Set the width of columns D to F Sheet1.Columns("D:F").ColumnWidth = 4 ' Set the font size of row 5 to 18 Sheet1.Rows(5).Font.Size = 18 End Sub
Using Range in place of Worksheet
You can also use Cells, Rows and Columns as part of a Range rather than part of a Worksheet. You may have a specific need to do this but otherwise I would avoid the practice. It makes the code more complex. Simple code is your friend. It reduces the possibility of errors.
The code below will set the second column of the range to bold. As the range has only two rows the entire column is considered B1:B2
' https://excelmacromastery.com/ Public Sub UseColumnsInRange() ' This will set B1 and B2 to be bold Sheet1.Range("A1:C2").Columns(2).Font.Bold = True End Sub
You can download all the code for this post from the top of this article.
Reading Values from one Cell to another
In most of the examples so far we have written values to a cell. We do this by placing the range on the left of the equals sign and the value to place in the cell on the right. To write data from one cell to another we do the same. The destination range goes on the left and the source range goes on the right.
The following example shows you how to do this:
' https://excelmacromastery.com/ Public Sub ReadValues() ' Place value from B1 in A1 Sheet1.Range("A1").Value2 = Sheet1.Range("B1").Value2 ' Place value from B3 in sheet2 to cell A1 Sheet1.Range("A1").Value2 = Sheet2.Range("B3").Value2 ' Place value from B1 in cells A1 to A5 Sheet1.Range("A1:A5").Value2 = Sheet1.Range("B1").Value2 ' You need to use the "Value" property to read multiple cells Sheet1.Range("A1:A5").Value2 = Sheet1.Range("B1:B5").Value2 End Sub
As you can see from this example it is not possible to read from multiple cells. If you want to do this you can use the Copy function of Range with the Destination parameter
' https://excelmacromastery.com/ Public Sub CopyValues() ' Store the copy range in a variable Dim rgCopy As Range Set rgCopy = Sheet1.Range("B1:B5") ' Use this to copy from more than one cell rgCopy.Copy Destination:=Sheet1.Range("A1:A5") ' You can paste to multiple destinations rgCopy.Copy Destination:=Sheet1.Range("A1:A5,C2:C6") End Sub
The Copy function copies everything including the format of the cells. It is the same result as manually copying and pasting a selection. You can see more about it in the Copying and Pasting Cells section.
Using the Range.Resize Method
When copying from one range to another using assignment(i.e. the equals sign), the destination range must be the same size as the source range.
Using the Resize function allows us to resize a range to a given number of rows and columns.
For example:
' https://excelmacromastery.com/ Sub ResizeExamples() ' Prints A1 Debug.Print Sheet1.Range("A1").Address ' Prints A1:A2 Debug.Print Sheet1.Range("A1").Resize(2, 1).Address ' Prints A1:A5 Debug.Print Sheet1.Range("A1").Resize(5, 1).Address ' Prints A1:D1 Debug.Print Sheet1.Range("A1").Resize(1, 4).Address ' Prints A1:C3 Debug.Print Sheet1.Range("A1").Resize(3, 3).Address End Sub
When we want to resize our destination range we can simply use the source range size.
In other words, we use the row and column count of the source range as the parameters for resizing:
' https://excelmacromastery.com/ Sub Resize() Dim rgSrc As Range, rgDest As Range ' Get all the data in the current region Set rgSrc = Sheet1.Range("A1").CurrentRegion ' Get the range destination Set rgDest = Sheet2.Range("A1") Set rgDest = rgDest.Resize(rgSrc.Rows.Count, rgSrc.Columns.Count) rgDest.Value2 = rgSrc.Value2 End Sub
We can do the resize in one line if we prefer:
' https://excelmacromastery.com/ Sub ResizeOneLine() Dim rgSrc As Range ' Get all the data in the current region Set rgSrc = Sheet1.Range("A1").CurrentRegion With rgSrc Sheet2.Range("A1").Resize(.Rows.Count, .Columns.Count).Value2 = .Value2 End With End Sub
Reading Values to variables
We looked at how to read from one cell to another. You can also read from a cell to a variable. A variable is used to store values while a Macro is running. You normally do this when you want to manipulate the data before writing it somewhere. The following is a simple example using a variable. As you can see the value of the item to the right of the equals is written to the item to the left of the equals.
' https://excelmacromastery.com/ Public Sub UseVariables() ' Create Dim number As Long ' Read number from cell number = Sheet1.Range("A1").Value2 ' Add 1 to value number = number + 1 ' Write new value to cell Sheet1.Range("A2").Value2 = number End Sub
To read text to a variable you use a variable of type String:
' https://excelmacromastery.com/ Public Sub UseVariableText() ' Declare a variable of type string Dim text As String ' Read value from cell text = Sheet1.Range("A1").Value2 ' Write value to cell Sheet1.Range("A2").Value2 = text End Sub
You can write a variable to a range of cells. You just specify the range on the left and the value will be written to all cells in the range.
' https://excelmacromastery.com/ Public Sub VarToMulti() ' Read value from cell Sheet1.Range("A1:B10").Value2 = 66 End Sub
You cannot read from multiple cells to a variable. However you can read to an array which is a collection of variables. We will look at doing this in the next section.
How to Copy and Paste Cells
If you want to copy and paste a range of cells then you do not need to select them. This is a common error made by new VBA users.
Note: We normally use Range.Copy when we want to copy formats, formulas, validation. If we want to copy values it is not the most efficient method.
I have written a complete guide to copying data in Excel VBA here.
You can simply copy a range of cells like this:
Range("A1:B4").Copy Destination:=Range("C5")
Using this method copies everything – values, formats, formulas and so on. If you want to copy individual items you can use the PasteSpecial property of range.
It works like this
Range("A1:B4").Copy Range("F3").PasteSpecial Paste:=xlPasteValues Range("F3").PasteSpecial Paste:=xlPasteFormats Range("F3").PasteSpecial Paste:=xlPasteFormulas
The following table shows a full list of all the paste types
Paste Type |
---|
xlPasteAll |
xlPasteAllExceptBorders |
xlPasteAllMergingConditionalFormats |
xlPasteAllUsingSourceTheme |
xlPasteColumnWidths |
xlPasteComments |
xlPasteFormats |
xlPasteFormulas |
xlPasteFormulasAndNumberFormats |
xlPasteValidation |
xlPasteValues |
xlPasteValuesAndNumberFormats |
Reading a Range of Cells to an Array
You can also copy values by assigning the value of one range to another.
Range("A3:Z3").Value2 = Range("A1:Z1").Value2
The value of range in this example is considered to be a variant array. What this means is that you can easily read from a range of cells to an array. You can also write from an array to a range of cells. If you are not familiar with arrays you can check them out in this post.
The following code shows an example of using an array with a range:
' https://excelmacromastery.com/ Public Sub ReadToArray() ' Create dynamic array Dim StudentMarks() As Variant ' Read 26 values into array from the first row StudentMarks = Range("A1:Z1").Value2 ' Do something with array here ' Write the 26 values to the third row Range("A3:Z3").Value2 = StudentMarks End Sub
Keep in mind that the array created by the read is a 2 dimensional array. This is because a spreadsheet stores values in two dimensions i.e. rows and columns
Going through all the cells in a Range
Sometimes you may want to go through each cell one at a time to check value.
You can do this using a For Each loop shown in the following code
' https://excelmacromastery.com/ Public Sub TraversingCells() ' Go through each cells in the range Dim rg As Range For Each rg In Sheet1.Range("A1:A10,A20") ' Print address of cells that are negative If rg.Value < 0 Then Debug.Print rg.Address + " is negative." End If Next End Sub
You can also go through consecutive Cells using the Cells property and a standard For loop.
The standard loop is more flexible about the order you use but it is slower than a For Each loop.
' https://excelmacromastery.com/ Public Sub TraverseCells() ' Go through cells from A1 to A10 Dim i As Long For i = 1 To 10 ' Print address of cells that are negative If Range("A" & i).Value < 0 Then Debug.Print Range("A" & i).Address + " is negative." End If Next ' Go through cells in reverse i.e. from A10 to A1 For i = 10 To 1 Step -1 ' Print address of cells that are negative If Range("A" & i) < 0 Then Debug.Print Range("A" & i).Address + " is negative." End If Next End Sub
Formatting Cells
Sometimes you will need to format the cells the in spreadsheet. This is actually very straightforward. The following example shows you various formatting you can add to any range of cells
' https://excelmacromastery.com/ Public Sub FormattingCells() With Sheet1 ' Format the font .Range("A1").Font.Bold = True .Range("A1").Font.Underline = True .Range("A1").Font.Color = rgbNavy ' Set the number format to 2 decimal places .Range("B2").NumberFormat = "0.00" ' Set the number format to a date .Range("C2").NumberFormat = "dd/mm/yyyy" ' Set the number format to general .Range("C3").NumberFormat = "General" ' Set the number format to text .Range("C4").NumberFormat = "Text" ' Set the fill color of the cell .Range("B3").Interior.Color = rgbSandyBrown ' Format the borders .Range("B4").Borders.LineStyle = xlDash .Range("B4").Borders.Color = rgbBlueViolet End With End Sub
Main Points
The following is a summary of the main points
- Range returns a range of cells
- Cells returns one cells only
- You can read from one cell to another
- You can read from a range of cells to another range of cells.
- You can read values from cells to variables and vice versa.
- You can read values from ranges to arrays and vice versa
- You can use a For Each or For loop to run through every cell in a range.
- The properties Rows and Columns allow you to access a range of cells of these types
What’s Next?
Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.
Related Training: Get full access to the Excel VBA training webinars and all the tutorials.
(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)
Even after 20+ years of working with Excel & VBA, and teaching others the “basics and more” on a regular basis, once I stumbled onto your site I’ve found myself returning often to reference (or recommend) your “complete guides” (mainly Collections & Dictionaries). Comprehensive but easy to understand.
Again – great site, thanks.
I have enjoyed your informative review. You explain things well.
Hi Paul
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
If Sheets(“Savings (2)”).Range(“A1”).Value “” Then
Sheets(“Savings (2)”).Range(“A1”).Value = “”
Exit Sub
End If
If Sheets(“Savings (2)”).Range(“D6:D20”).Value “” And Sheets(“Savings (2)”).Range(“E6:U20”).Value = “” Then
Cancel = True
MsgBox “Please fill in all cells.”
End If
End Sub
This is the code that I’ve written. The idea is to get the user to fill in cells E to U if cell D is filled, before they can save the file. My issue is that I can’t seem to get the code to work if I put in the range like above. It does work however if I just put in one cell e.g If Sheets(“Savings (2)”).Range(“D6”).Value “” And Sheets(“Savings (2)”).Range(“E6”).Value.
Can you tell me what is the issue?
I replied to your other comment asking the same question.
Multiple cells in a range is equivalent to a 2D array. You cannot compare an array to a single value.
You need to read through the array and check each value.
I read this hoping to find how to do something specific and did not find it.
I am writing a macro with a list of ranges as arguments (R0, R1, R2) . All but the first are optional.
I have an array in the macro which is of type range (Dim Rx(2) as range) and want to copy the three optional arguments into the array so that I can process them in a loop. When I tried R(0) = R0 it failed.
Here is the relevant snippet of code:
Function Test ( _
R0 As Range _
, Optional R1 As Range = Nothing _
, Optional R2 As Range = Nothing _
) As String
Dim R(9) As Range
R(0) = R0 ‘ fails on this line
R(1) = R1
R(2) = R2
End Function
Any ideas? Thanks.
Hi Steve,
You need to use Set when assigning one range to another.
Set R(0) = R0
The following code works in VBA directly, returning the contents of the first cell in the current region. But if I call it from Excel by entering ‘=testf(C102)’ into a cell it only returns that cell, not the current region. I have tried it with both byref and byval with the same result.
How can the same code return two different results depending on whether it is called from VBA or from Excel?
Sub tests()
Dim x As String
Dim rg As Range
Set rg = Range(“C102”)
x = testf(rg)
End Sub
Function testf(ByVal rgv As Range) As String
Dim rngV As Range
Dim addrV As String
addrV = rgv.Address
Set rngV = Range(addrV).CurrentRegion
Debug.Print rngV.Cells(1, 1).Value2
testf = rngV.Cells(1, 1).Value2
End Function
Hi Steve,
It’s an issue with CurrentRegion in User Defined Functions. If you google it you will see some discussions about it.
Unfortunately you will need to create a workaround.
Paul
Thank you for this great work! Your blog helped me a lot to start my work in VBA.
I’ve one little suggestion: inside the code block underneath “You can do this using a For Each loop shown in the following code” you may want to clarify the comment inside the code block to “Print address of cells that contain negative value”. It’s not the address that may be negative 😉
can we use cell or range property in trim function in vba
yes, for example:
Trim(Range(“A1”).Value)
Hi, Paul
maybe you can help me:
I want to run a sub, which gets data and sets a title, containing a value from a cell which is contains a value from a view from SQL-Server. This must be refreshed first.
Set wk = ActiveWorkbook
wk.RefreshAll
wk.Sheets(“Parameter”).Calculate ‘ first try to refresh cell
Application.Wait (Now + TimeValue(“0:00:01”)) ‘ second try to refresh cell
MsgBox wk.Sheets(“Parameter”).Range(“C2”).Value
The cell is refreshed only AFTER the Msgbox is displayed with the old value…
Paul, is there some way, besides retrieving and comparing every cell in every row and column on an entire sheet, to find whether a certain string exists anywhere in the sheet? That is, is there something like a “populated range” variable (or “max populated row#” x “max populated column#”) that I could use to limit the range I need to check when doing a string search in a sheet?
Without this, there are > 1M rows by 16384 columns that would all need to be searched cell-by-cell.
I don’t recall ever seeing reference to something like this, but it’s hard to believe that the built-in Excel Search function actually does it the brute-force way.
I could probably search the binary file for the string instead if I only wanted to know if it existed (and the string were unique enough), but then I wouldn’t be able to return a cell location reference.
You can use UsedRange to get all the cellshttps://excelmacromastery.com/wp-admin/edit-comments.php#comments-form used on a given worksheet.
Hi
For example, in column A we have A1=1; A7=5; A12=8;A21=6 and so on.
Task:
How to formulate to fill the following empty cells from A2 to A7 with 1, from A8 to A12 with 5 and so on?
Thank you
Hi Paul, great site! Your page on dictionaries was particularly helpful for me.
Ended up here while looking for something else and thought I’d suggest that a short mention of the intersect and union methods on this page would help some people here I’m sure.
Hi Mark!
Thank you very much for this website, it is really clear and includes a lot of functions which I will have to use in the future and had no idea how to do. Nevertheless I have a very specific question which is not treated here. In the Macro I am working on, I am calling in all the functions the exact position of a cell. For instance: Range (cells(11,”C”)). Nevertheless I have found a problem and is that there is a possibility that in future steps I will have to eliminate or add new columns in the sheet I am working on, thus I will have to change function by function the column. Is there a way to name a column and then use that name in the Cells function? or any other solution to my problem?
You can use a named range. Create a named range using Name Manager under the formula tab in Excel.
You can use it like Range(“MyNamedRange”)
I’ve been having a difficult time trying to get the syntax correct. What I want to do is select 2 non adjacent cells before formatting them. They are relative to the existing selected cell.
Many efforts different ways, but I am missing something!
Sub SelectHighlight()
Dim CurrentRw As Integer
Dim CurrentColumnLetter As String
Dim ColumnLetter2 As String
Dim ColumnLetter3 As String
Dim ColumnLetter4 As String
Dim myRange As Range
CurrentRw = ActiveCell.Row
CurrentCl = ActiveCell.Column
CurrentColumnLetter = Split(Cells(1, ActiveCell.Column).Address, “$”)(1)
Cl2 = ActiveCell.Column + 2
Cl3 = ActiveCell.Column + 4
Cl4 = ActiveCell.Column + 6
ColumnLetter2 = Split(Cells(1, ActiveCell.Column + 2).Address, “$”)(1)
ColumnLetter3 = Split(Cells(1, ActiveCell.Column + 4).Address, “$”)(1)
ColumnLetter4 = Split(Cells(1, ActiveCell.Column + 6).Address, “$”)(1)
‘ActiveSheet.Range(Cells(CurrentRw, CurrentCl), Cells(CurrentRw, Cl2)).Select
‘ Range(” & ColumnLetter2 & CurrentRw & “, ” & ColumnLetter4 & CurrentRw & “).Select
‘Range(“ColumnLetter2 & CurrentRw , ColumnLetter4 & CurrentRw”).Select
Range [ ColumnLetter2 & CurrentRw & “,” & ColumnLetter4 & CurrentRw ].Select
‘Set myRange = Union(.Cells(CurrentRw, CurrentCl), .Cells(CurrentRw, Cl2))
End Sub
You can use Offset to count from the current cell. E.g. Range(“A1”).Offset(1,1) returns B2.
Hi Paul, just discovered your site
The following code snip is used to place values in the sheet “Easement_Memo”, building a 3 column table.
I need to refer to the cells as .Cells(row,column) where row and column are integer variables.
I then need to select a range – single cell – using the .cells(row,column) as both the start and end of the range.
I looked at your example and have tried to “copy” it, but it is failing at the range select.
oWrkBk.Worksheets(“Easement_Memo”).Cells(Easement_Memo_Lines + 1, 1) = il
oWrkBk.Worksheets(“Easement_Memo”).Cells(Easement_Memo_Lines + 1, 2) = Replace(EMPs(j), Chr(34), “”)
EasementDoc = Replace(EMPs(j), Chr(34), “”) ‘ a path and file
‘ select the range and insert the word doc – with formatting, into this range ‘ get word doc – EasementDoc and insert into a single cell range – this fails
oWrkBk.Worksheets(“Easement_Memo”).Range(oWrkBk.Worksheets(“Easement_Memo”).Cells(Easement_Memo_Lines + 1, 3), oWrkBk.Worksheets(“Easement_Memo”).Cells(Easement_Memo_Lines + 1, 3)).Select
oWrkBk.Worksheets(“Easement_Memo”).OLEObjects.Add(FileName:=EasementDoc, Link:=False, DisplayAsIcon:=False).Select
Michael Lewis
Hi Paul, how do I make a range out of 2 cell addresses? Below is my coding:
Dim Found As Range
Dim Found1 As Range
‘
Set Found = Cells.Find(What:=”Pay Frequency Totals: Biweekly”, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
Set Found1 = Cells.Find(What:=”Total Employees – Biweekly: 41″, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
Range(Found & “:” & Found1).Select ‘ <<< the problem is this code here. how do I change this to the correct one?
Selection.Copy
Range(Found).Offset(0, -1).Select
ActiveSheet.Paste
You don’t need to create a range from both of them.
You can assign them individually e.g.
ActiveSheet.Range(“A1”).value = Range(Found).Offset(0, -1).Value
Thanks for this article! I would suggest to add something to make it fully complete. I think it would be important to mention that the Cells property can also take a string as its second argument. ie.
ActiveSheet.Cells(2, “B”).Select
Would do the same thing as :
ActiveSheet.Cells(2, 2).Select
Hello Paul
I have one issue with my code listed below:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim X As Integer
Dim y As Integer
y = 7
X = Sheet2.UsedRange.Rows.Count
Do Until y > X
If Sheet2.Cells(y, 3).Value = “OPEN” Then
Sheet2.Cells(y, 3).Interior.Color = 255
ElseIf Sheet2.Cells(y, 3).Value = “CLOSE” Then
Sheet2.Cells(y, 3).Interior.Color = RGB(0, 176, 80)
ElseIf Sheet2.Cells(y, 3).Value = “N/A” Then
Sheet2.Cells(y, 3).Interior.Color = RGB(255, 255, 0)
End If
If Sheet2.Cells(y, 3).Value “OPEN” And Sheet2.Cells(y, 4).Value “OPEN” And Sheet2.Cells(y, 5).Value “OPEN” And Sheet2.Cells(y, 6).Value “OPEN” And Sheet2.Cells(y, 7).Value “OPEN” And Sheet2.Cells(y, 8).Value “OPEN” Then
Sheet2.Cells(y, 11).Value = “CLOSED”
Else:
Sheet2.Cells(y, 11).Value = “OPEN”
End If
y = y + 1
Loop
End Sub
when i’m running this code the sheet hanging up and excel closed I don’t know why ? could you help me for finding the mistake
thanks
Hassan,
Simply put, assigning a new value to Sheet2.Cells(y,11) is causing the Worksheet_Change event to fire again resulting in a recursive loop that eventually consumes all resources and hence crashes. If the Worksheet_Change routine itself makes changes to the Worksheet you need to disable application events during the Worksheet_Change routine and re-enable them on the way out. Another alternative might be to inspect Target parameter and skip processing if the change is being made to Column 11 on the assumption that it is this routine that is making the change.
Hi Paul,
Your post are very effective, thank for sharing with us your great knowledge ☺️
Thanks Neeraj
This page helped me out today. Thanks for your hard work!
Hello.
I was wondering if you know how to output the following collected cells to 1 single 1 line string, without Spaces
Sub UnionExample()
Dim Rng1, Rng2, Rng3, Rng4, Rng5, Rng6 As Range
Set Rng1 = Range(“A1,B1,C1,D1,E1,F1,G1,H1,I1,J1,K1,L1,M1,N1,O1,P1,Q1,R1,S1,T1,U1,V1,W1,X1,Y1,Z1”)
Set Rng2 = Range(“AA1,AB1,AC1,AD1,AE1,AF1,AG1,AH1,AI1,AJ1,AK1,AL1,AM1,AN1,AO1,AP1,AQ1,AR1,AS1,AT1,AU1,AV1,AW1,AX1,AY1,AZ1”)
Set Rng3 = Range(“BA1,BB1,BC1,BD1,BE1,BF1,BG1,BH1,BI1,BJ1,BK1,BL1,BM1,BN1,BO1,BP1,BQ1,BR1,BS1,BT1,BU1,BV1,BW1,BX1,BY1,BZ1”)
Set Rng4 = Range(“CA1,CB1,CC1,CD1,CE1,CF1,CG1,CH1,CI1,CJ1,CK1,CL1,CM1,CN1,CO1,CP1,CQ1,CR1,CS1,CT1,CU1,CV1,CW1,CX1,CY1,CZ1”)
Set Rng5 = Range(“DA1,DB1,DC1,DD1,DE1,DF1,DG1,DH1,DI1,DJ1,DK1,DL1,DM1,DN1,DO1,DP1,DQ1,DR1,DS1,DT1,DU1,DV1,DW1,DX1,DY1,DZ1”)
Set Rng6 = Range(“EA1,EB1,EC1,ED1,EE1,EF1,EG1,EH1,EI1,EJ1,EK1,EL1,EM1,EN1,EO1,EP1,EQ1,ER1,ES1,ET1,EU1,EV1,EW1,EX1,EY1,EZ1”)
Union(Rng1, Rng2, Rng3, Rng4, Rng5, Rng6).Select
End Sub
_________
I found a script like this:
Sub testwrite()
Dim Rng1, Rng2, Rng3, Rng4, Rng5, Rng6 As Range
Dim newRng As Range
Dim Path As String
Dim r As Variant
Dim i As Integer
Dim rows As Integer
Path = ActiveWorkbook.Path
Set rng1 = ActiveSheet.Range(“A2:A25”)
rows = rng1.Count
Dim output As String
For i = 1 To rows Step 1
output = output & rng1.rows(i).Value & “,” & rng2.rows(i).Value & vbCrLf
Next i
Open Path & “\text_data3.txt” For Output As #1
Print #1, output
Close
End Sub
………..but could not make it work..
I simply want the first cell in all rows to join in 1 string, and if possible remove any parts consisting of “|00|” so the “empty” cells are not included.
Hope you can help.
Bård
Norway
The following macro sorts columns A – F based on values in Columns B and D.
I plan to use similar macros for other tabs in the same spreadsheet.
The first row for each tab will be different and will vary as existing rows are deleted and/or new rows are added.
I would like to have the references to A25, B25, D25 and F25 be variables.
This will allow the values to be placed in a cell on each tab.
Having the value in a cell will:
Allow for changes to that value as changes are made to rows on the tab
Eliminate the need to change the macro as changes are made to rows on the tab
Thank you.
ActiveWorkbook.Worksheets(“Pending Debit”).Select
ActiveWorkbook.Worksheets(“Pending Debit”).Sort.SortFields.Clear
ActiveWorkbook.Worksheets(“Pending Debit”).Sort.SortFields.Add2 _
Key:=Range(“B25”, Range(“B25”).End(xlDown)), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:= _
xlSortNormal
ActiveWorkbook.Worksheets(“Pending Debit”).Sort.SortFields.Add2 _
Key:=Range(“D25”, Range(“D25”).End(xlDown)), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets(“Pending Debit”).Sort
.SetRange Range(“A25”, Range(“F25”).End(xlDown))
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
ActiveWorkbook.Worksheets(“Pending Debit”).Range(“B25”).End(xlDown).Offset(1, 0).Select
Hi there!
Is there a possibility to change the F3 in Range(“F3”) in some way like this:
X= “C” + A1 (in A1 is the value 22; so X should be C22)
Range(X) (which should be like Range(“C22”))
Is something like this possible?
Hi Paul,
Thank you for the great work and insight to the various topics at your site.
In regards to cells and ranges, I hope you can help me with a code error, that I am struggling to sort out;
– Run-time error ‘424’: Object required.
Sub writedata_01()
Dim j As Long
j = Sheet5.Range(“C2”).value2
*Debug error at this line*
Sheet1.Range(“L_1”).Value2 = Sheet2.Range(“EARDB”).Cells(j, [EARDB[L_1]].Column)
Sheet1.Range(“L_2”).Value2 = Sheet2.Range(“EARDB”).Cells(j, [EARDB[L_2]].Column)
…
The EARDB is a named table (Range) consisting of a huge amount of data, of which I wants to extract some of the defined columns e.g.(L_1, L_2 etc.) to specific named cells in a different sheet for a summary of the information related to a case. J being the specific case row line.
The workbook is working fine when the workbook is open and the code is executed, but comes with the error on exit.
Could you give me an insight to where it went wrong?
Great post Paul. Thank you for pointing me the right direction. I have a problem – I am writing code in Access to output the results of a query to an excel file. Formatted as under
name1; name2; name3 (field of study); name4; name5 (field of study);
name3 needs to be bold and field of study needs to be green and bold. the string in the cell can be 1000 characters.
I have achieved something like this but I keep getting error—here is my code snip
With objSht.Cells(Xrow, Xcol + ifield).Activate
With ActiveCell
.Characters(stM, enM – stM + 1).Font.FontStyle = “Bold”
End With
If InStr(1, aLst1M, “(CB)”, vbTextCompare) > 0 Then
sP = InStr(1, aLst1M, “(CB)”, vbTextCompare) + 1
ActiveCell.Characters(sP, 2).Font.Color = &HFF&
End If
If InStr(1, aLst1M, “(TO)”, vbTextCompare) > 0 Then
sP = InStr(1, aLst1M, “(TO)”, vbTextCompare) + 1
ActiveCell.Characters(sP, 2).Font.Color = &HFF00&
End If
If InStr(1, aLst1M, “(CPC)”, vbTextCompare) > 0 Then
sP = InStr(1, aLst1M, “(CPC)”, vbTextCompare) + 1
ActiveCell.Characters(sP, 3).Font.Color = &HFF0000
End If
End With
There are 2 different constructs With ActiveCell and Without the With keyword. Sometimes it fails with error 91 Object undefined……etc. but sometimes on the second or third it works without any change to code. Driving me crazy!
I will really appreciate your advice and happy to share a screen to show you what happens.
Sandeep
Hi Paul. I have to columns. One with either 0 or positive weights and the other asset class. I want to create a formulae where I want to get only the positive weights and the corresponding asset class and paste in another column and row. How would I do this?
Thank you Paul, this was very help. I’ve inherited someone else’s work and am trying to debug a few things. My question is: Why would someone code “Range [-2] (“L1″).Select…” ? What is the purpose of placing a negative 2 after the Range function? Thank you again.
I’m not sure because your code isn’t valid VBA code.
Dear Paul,
I am infinitely grateful for your articles and studies.
I’m a retiree with a small retirement, I can’t pay, but your free articles will help me learn code writing.
Do not stop!
Thank you very much, Paul.
Regards,
László
Thanks László.
Hi Paul,
your guide has already been really helpfull for me. However I’m stuck with a new problem now.
I would like to search for the first empty row (variable material code) in my file. The difficult part here is that this might be between 2 completed lines (like line with position = 4). So just going to the end and do + 1 in row count does not work.
Can you please help me out?
Draw Row Position Material Code Batchnr
1 1 1 M8A2000354LA 8A2050820
1 1 2 M8A2001063LA 8A2042923
1 1 3 M8A2001279AA 8A2051212
1 1 4
1 1 5
1 1 6 M8A2001220JH 8A2050417
1 1 7 M8A2001279DF 8A2051212
1 1 8
You can use Data = VBA.Array(1, 2, 3) instead of Data = Array(1, 2, 3) to ensure that the array will always be zero-based (Option Base related). Is there a reason behind using Dim rg As Excel.Range instead of Dim rg As Range?
Hi Paul!
I’m a beginner to excel vba.I want to write a user defined function in vba
This is my code for summing the even numbers for a range.
Function SUMEVENNUMBERS(rng As Range)
Dim cell As Range
For Each cell In rng
Next cell
If cell.Value Mod 2 = 0 Then
SUMEVENNUMBERS = SUMEVENNUMBERS + cell.Value
End If
End Function
I’m getting error that the value used in the formula is of wrong data type.Can somebody help me to fix this.
Thank you