Vba range from string excel

Is there anyway to convert a string value to a Range object ? I’m having a function which takes a Range object as a argument and need to pass a single string parameter to it

Thank You

asked May 26, 2010 at 9:19

nimo's user avatar

3

A string with a cell address? if so:

Dim r As Range: Set r = Range("B3")
MsgBox r.ColumnWidth

answered May 26, 2010 at 9:27

Alex K.'s user avatar

Alex K.Alex K.

170k30 gold badges263 silver badges286 bronze badges

4

I don’t like this one bit, but if you can’t change the function that requires a range, you could create a function that converts a string to a range. You’d want to be sure that the only thing the first function cares about is the Value or Text properties.

Function FuncThatTakesRange(rng As Range)

    FuncThatTakesRange = rng.Value

End Function

Function ConvertStringToRange(sInput As String) As Range

    Dim ws As Worksheet

    Set ws = Workbooks.Add.Sheets(1)

    ws.Range("A1").Value = sInput

    Set ConvertStringToRange = ws.Range("A1")

    Application.OnTime Now + TimeSerial(0, 0, 1), "'CloseWB """ & ws.Parent.Name & """'"

End Function

Sub CloseWb(sWb As String)

    On Error Resume Next
        Workbooks(sWb).Close False

End Sub

Use in the Immediate Window like

?functhattakesrange(convertstringtorange("Myvalue"))

answered May 26, 2010 at 14:10

Dick Kusleika's user avatar

Dick KusleikaDick Kusleika

32.5k4 gold badges51 silver badges73 bronze badges

Here is my solution that involves no need for a new function.

1.Make dynamic string variable first

2.Then finalize it by creating a range object out of this string via a range method: Set dynamicrange= range (dynamicstring)

You can manipulate dynamicstring as you want to, I just kept it simple so that you can see that you can make range out of a string variable.


Sub test()

Dim dynamicrangecopystring As String
Dim dynamicrangecopy As range
dynamicrangecopystring = "B12:Q12"
Set dynamicrangecopy = range(dynamicrangecopystring)

End Sub

answered Nov 21, 2017 at 8:53

sedreddin's user avatar

Why not change the function argument to a variant and then in the function determine Using VarType etc) if you have been passed a Range and use error handling to check for a string which can be converted to a range or a string that cannot be converted to a range ?

answered May 26, 2010 at 19:06

Charles Williams's user avatar

Charles WilliamsCharles Williams

23.1k5 gold badges37 silver badges38 bronze badges

This simple function will convert string arguments into a range object, usable in other excel functions.

Function TXT2RNG(text) As Variant

Set TXT2RNG = Range(text)

End Function

answered Aug 15, 2016 at 17:03

Andrew's user avatar

1

Let’s say Sheet1!A1 has the text value «Sheet1!B1» and Sheet1!B1 has the value «1234». The following code will use the range address stored as text in A1 as an input and copy the range B1 to A2:

Sub Tester()

  Sheet1.Range(Range("A1")).Copy

  Sheet1.Range("A2").PasteSpecial xlPasteAll

End Sub

answered Nov 19, 2013 at 16:59

Daniel H's user avatar

This is kind of silly, but I’ve been stuck for a while in this simple statement:

    Dim range1 as Range
    Dim mysheet as String
    Dim myrange as String

    mysheet = "Sheet1"
    range = "A1:A10"

range1 = Worksheets(mysheet).Range(myrange)

I’ve testing all the solutions that I’ve found on the internet as for example this, this and this, but nothing.

All the time it gives me errors: 1004 «Error defined by the application» or «object variable or with not set».

I have tried the following:

range1 = ThisWorkbook.Worksheets(mysheet).Range(myrange)

range1 = ActiveWorkbook.Worksheets(mysheet).Range(myrange)

range1 = Sheets(mysheet).Range(myrange) (and the combinations above)

range1 = Worksheets(mysheet).Range(Cells(1,1), Cells(1,10)) (and the combinations with This/Active workbook)

and

with This/ActiveWorkbook
range1 = .Worksheets(mysheet).Range(myrange)
end with

None have worked.

This is a REALLY silly thing, but I’ve been stuck for a while now :s

Can anyone help me?

Really thanks in advance.

Best regards,

  • #1

I’m currently trying to copy a dynamic range based on the row number of a selected listbox item. I’m able to get the row number of the selected listbox item from the data tab in my file. I, however, am stuck when it comes to copying a fixed column / varying row range from this tab and copying it over to another tab.

Private Sub CommandButton2_Click()
Dim ID As Long
Dim Row As Long
Dim Cnt As Long
Dim SearchTermsStr As String
Dim SearchTermsRng As Range

‘Get Row Number’
Cnt = InStr(1, ListBox1.Value, «-«)
ID = Left(ListBox1.Value, Cnt — 1)
On Error Resume Next
Row = Application.WorksheetFunction.Match(ID, Sheets(«Data»).Range(«B1:B200»), 0)
On Error GoTo 0

SearchTermsStr = «F» & Row & «:0» & Row
SearchTermsRng = Range(SearchTermsStr)
Sheets(«Data»).Select
Range(SearchTermsRng).Copy
Sheets(«InputORAdjustNewProduct»).Select
Range(«B9:K9»).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False

End Sub

SearchTermsRng is returing «Nothing» but the SearchTermsStr returns «F3:O3»

Any ideas what I might be doing wrong here?

Back into an answer in Excel

Use Data, What-If Analysis, Goal Seek to find the correct input cell value to reach a desired result

  • #2

Are you sure that is a letter O in the formula and not a Zero?

  • #3

Try
SearchTermsStr = «F» & Row & «:O & Row
SET SearchTermsRng = Range(SearchTermsStr)

  • #4

Turns out the ‘O’ was a zero (embarrassing) . I had changed it but it still didn’t work.

I took SearchTermsRng out and simply used SearchTermsStr as the range and that worked fine.

Private Sub CommandButton2_Click()
Dim ID As Long
Dim Row As Long
Dim Cnt As Long
Dim SearchTermsStr As String

‘Get Row Number’
Cnt = InStr(1, ListBox1.Value, «-«)
ID = Left(ListBox1.Value, Cnt — 1)
On Error Resume Next
Row = Application.WorksheetFunction.Match(ID, Sheets(«Data»).Range(«B1:B200»), 0)
On Error GoTo 0

SearchTermsStr = «F» & Row & «:O» & Row
Sheets(«Data»).Select
Range(SearchTermsStr).Copy
Sheets(«InputORAdjustNewProduct»).Select
Range(«B9:K9»).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False

End Sub

  • #5

Welcome to the board.

You don’t need to select ranges or sheets to perform actions on them. Your entire final section of code could be written as:

Sheets(«InputORAdjustNewProduct»).Range(«B9:K9»).Value = Sheets(«Data»).Range(Cells(Row, 6), Cells(Row, 15)).Value

  • #6

Well how about that!?

Thanks Neil. I will definitely use that method rather than my lengthy one.

  • #7

If the fields on my data tab are both text and values, how would I alter your suggestion?

  • #8

If the fields on my data tab are both text and values, how would I alter your suggestion?

Why would that make a difference? The code I posted is the equivalent of the below, without making use of the clipboard:
Range(«Range1»).Copy
Range(«Range2»).PasteSpecial xlValues

  • #9

it doesn’t change a thing. Value is a property that means «What is in the cell»

  • #10

Why would that make a difference? The code I posted is the equivalent of the below, without making use of the clipboard:
Range(«Range1»).Copy
Range(«Range2»).PasteSpecial xlValues

I replaced my code with yours…It didn’t work for some reason, that is why I was wondering if I needed to specify.

Private Sub CommandButton2_Click()
Dim ID As Long
Dim Row As Long
Dim Cnt As Long

‘Get Row Number’
Cnt = InStr(1, ListBox1.Value, «-«)
ID = Left(ListBox1.Value, Cnt — 1)
On Error Resume Next
Row = Application.WorksheetFunction.Match(ID, Sheets(«Data»).Range(«B1:B200»), 0)
On Error GoTo 0

Sheets(«InputORAdjustNewProduct»).Range(«B9:K9»).Value = Sheets(«Data»).Range(Cells(Row, 6), Cells(Row, 15)).Value

End Sub

6StringJazzer

mumps


    • #1

    I’m *trying* to get a range of cells activated so the macro I’m writing can go off and create a graph or load the graph wizard.

    The sheet is set out so that B4 — M4 are the months in the year, A5 — A24 are the possible different options to choose from, theres a button on the page that loads a user form on it. The form contains a list box, that gets populated with the values in the A5-A24 range. When the user selects the different options they want and click a button, I want the cells that are relevant to be highlighted.

    So for example if the user selected option 1, A5- M5 would get highlighted, and the the chart wizard would load, I know its a lot easier to simply highlighted the cells you want with the mouse and the run the wizard, but I want to set the chart values, title etc and I want to learn how its done.

    From the code below, I would like to know how to add the String mlist as a range, or create a range during the With / For loop. I’ve been searching Google for a while now and because I’m new to VBA I’m just getting lost. If anyone can point me in the right direction with a link or sample code that would be great. I haven’t done anything with mRange yet, because I don’t know how / what to do :)

    Private Sub GenerateGraph_Click()
        ' finds selected items in ListBox1 in userform
        Dim Msg As String, i As Integer
        Dim mlist As String
        Dim mRange As Range
        
        Msg = ""
        With UserForm1.ListBox1
            For i = 0 To .ListCount - 1
                If .Selected(i) Then
                    mlist = mlist & "A" & i + 5 & ":M" & i + 5 & ","
                    Msg = Msg & .list(i) & Chr(13)
                End If
            Next i
        End With
        
        If Msg = vbNullString Then
            Msg = "Please select atleast one option from the selection"
            MsgBox Msg, , "Please select items."
        Else
            MsgBox mlist, , "Please select items."
        End If
    End Sub

    Display More

    • #2

    Re: Excel create range from string variable


    Quote from deathadder

    I’m *trying* to get a range of cells activated so the macro I’m writing can go off and create a graph or load the graph wizard.

    The sheet is set out so that B4 — M4 are the months in the year, A5 — A24 are the possible different options to choose from, theres a button on the page that loads a user form on it. The form contains a list box, that gets populated with the values in the A5-A24 range. When the user selects the different options they want and click a button, I want the cells that are relevant to be highlighted.

    So for example if the user selected option 1, A5- M5 would get highlighted, and the the chart wizard would load, I know its a lot easier to simply highlighted the cells you want with the mouse and the run the wizard, but I want to set the chart values, title etc and I want to learn how its done.

    From the code below, I would like to know how to add the String mlist as a range, or create a range during the With / For loop. I’ve been searching Google for a while now and because I’m new to VBA I’m just getting lost. If anyone can point me in the right direction with a link or sample code that would be great. I haven’t done anything with mRange yet, because I don’t know how / what to do :)

    Private Sub GenerateGraph_Click()
        ' finds selected items in ListBox1 in userform
        Dim Msg As String, i As Integer
        Dim mlist As String
        Dim mRange As Range
        
        Msg = ""
        With UserForm1.ListBox1
            For i = 0 To .ListCount - 1
                If .Selected(i) Then
                    mlist = mlist & "A" & i + 5 & ":M" & i + 5 & ","
                    Msg = Msg & .list(i) & Chr(13)
                End If
            Next i
        End With
        
        If Msg = vbNullString Then
            Msg = "Please select atleast one option from the selection"
            MsgBox Msg, , "Please select items."
        Else
            MsgBox mlist, , "Please select items."
        End If
    End Sub

    Display More

    Display More

    You create a range like so

    [vba]
    Set rng = Range(«A» & i + 5 & «:M» & i + 5)
    [/vba]

    • #3

    Re: Excel create range from string variable

    Sorry for the probably stupid question, but the

    Set rng = Range("A" & i + 5 & ":M" & i + 5)

    Would replace my

    mlist = mlist & "A" & i + 5 & ":M" & i + 5 & ","

    Then I could make it ‘active’, hightlight the cells, but doing

    At the end, where I’m display mlist in the MsgBox.

    Thanks for your reply!

    • #4

    Re: Excel create range from string variable


    Quote

    Sorry for the probably stupid question…

    No such thing IMO. However, what is the question?

    • #5

    Re: Excel create range from string variable


    Quote

    No such thing IMO. However, what is the question?

    If the ‘set rng’ posted by Bob Phillips would replace the line

    mlist = mlist & "A" & i + 5 & ":M" & i + 5 & ","

    in my With / For loop. I replaced that line, and it didn’t cause any errors, however how would I make the range active? Sorry if the term isn’t corrent.

    I tried:

    However that caused an error, which I’ll post later on.

    Thanks for the help so far!

    • #6

    Re: Excel create range from string variable

    Oh, ok. Use

    or the safest way would be

    Application.GoTo rng,True
    • #7

    Re: Excel create range from string variable

    Thanks for the reply and help Dave Hawley. It’s very much appreciated!

    I’ve just got a couple more questions. Whats the difference between:

    rng.Activate
    
    
    &
    
    
    Application.GoTo rng,True

    I know the GoTo ‘takes you’ to the range, however is that the only difference?

    The other thing is that the last range is the only one selected, how could I append ranges to it, instead of over writing them, incase more than one of the options in my list is selected.

    I’ve tried the following, with no luck, if you could point me in the direction of some doc’s that would be great :)

    Dim rng As Range
          
        With UserForm1.ListBox1
            For i = 0 To .ListCount - 1
                If .Selected(i) Then
                    rng = rng & Range("A" & i + 5 & ":M" & i + 5)
                    Msg = Msg & .list(i) & Chr(13)
                End If
            Next i
        End With
    • #8

    Re: Excel create range from string variable


    Quote

    I know the GoTo ‘takes you’ to the range, however is that the only difference?

    No. GoTo will take you top the range from ANY Worksheet, while Activate requires the Worksheet housing the range to be active. Also, the option True argument means the range is placed in the top left of the users screen.

    To activate multiple ranges you would use the Union Method, see example below

    Sub ActivateMultipleRanges()
    Dim lLoop As Long
    Dim rRange As Range
    Dim rAllRanges As Range
    
    
        Set rAllRanges = Range("A1")
            For lLoop = 1 To 3
                Set rRange = Choose(lLoop, Range("A1"), Range("D5:D10"), Range("C10:C15"))
                Set rAllRanges = Application.Union(rAllRanges, rRange)
        Next lLoop
        
    rAllRanges.Select
    End Sub

    Display More

    • #9

    Re: Excel create range from string variable

    Ah, thanks for correcting me on that one :)

    Thanks for the code sample too, I’ll let you know how I get along….

    • #10

    Re: Excel create range from string variable

    Hi Dave,

    Thanks for the help so far, the code sample you posted is very similiar to what I want to achieve, I want it to be user selected rows instead.

    I’ve attempted to add parts of your code to mine, however when I run it I get a run time error 424, object required, on the line.

    Set rRange = Choose(i, Range("B4:M4"), Range("A" & i + 5 & ":M" & i + 5))

    Could you have a look at the code below and let me know where I’m messing this up.

    Private Sub GenerateGraph_Click()
        ' finds selected items in ListBox1 in userform
        Dim Msg As String, i As Integer
        Dim rAllRanges As Range
        Dim rRange As Range
    
    
        Set rAllRanges = Range("B4:M4")
        
        Msg = ""
        With UserForm1.ListBox1
            For i = 0 To .ListCount - 1
                If .Selected(i) Then
                    Set rRange = Choose(i, Range("B4:M4"), Range("A" & i + 5 & ":M" & i + 5))
                    Msg = Msg & .list(i) & Chr(13)
                    Set rAllRanges = Application.Union(rAllRanges, rRange)
                End If
            Next i
        End With
        
        If Msg = vbNullString Then
            Msg = "Please select atleast one option from the selection"
            MsgBox Msg, , "Please select items."
        Else
            rAllRanges.Select
        End If
        
    End Sub

    Display More

    Thanks for all your help so far!

    • #11

    Re: Excel create range from string variable

    You are starting the loop at zero and then using Choose(i i must be 1 or higher

    • #12

    Re: Excel create range from string variable

    Hi,

    Sorry its been so long since I’ve replied, I’ve been really busy with different bits at the moment :)

    However I’m still having problems with the code, you said that starting from a number greater that 0 would help, however I’ve tried starting at 1, or doing the below, neither or which have helped, still the same error.

    Run-time error '424':
    
    
    Object Required

    Its probably something really stupid that I’m doing :) Could you try and point me in the right direction, once again.

    Private Sub GenerateGraph_Click()
        ' finds selected items in ListBox1 in userform
        Dim Msg As String, i As Integer
        Dim rAllRanges As Range
        Dim rRange As Range
    
    
        Set rAllRanges = Range("B4:M4")
        
        Msg = ""
        With UserForm1.ListBox1
            For i = 1 To .ListCount - 1
                If .Selected(i) Then
                    'Debug points to this line...
                    Set rRange = Choose(i, Range("B4:M4"), Range("A" & i + 5 & ":M" & i + 5))
                    Msg = Msg & .list(i) & Chr(13)
                    Set rAllRanges = Application.Union(rAllRanges, rRange)
                End If
            Next i
        End With
        
        If Msg = vbNullString Then
            Msg = "Please select atleast one option from the selection"
            MsgBox Msg, , "Please select items."
        Else
            rAllRanges.Select
        End If
        
    End Sub

    Display More

    Thanks for all your help so far, it’s really appreciated!

Return to VBA Code Examples

This tutorial will demonstrate how to split strings of text into cells in VBA.

Split String into Cells

In VBA, we can use the Split Function to split a string of text into an Array.

Note: We wrote an entire mega-guide to using the Split Function in VBA. We highly recommend that you check it out.

Then we can loop through the array, outputting the split text into Excel cells:

Sub SplitBySemicolonExample()
    'Define variables
    Dim MyArray() As String, MyString As String, I As Variant, N As Integer
    
    'Sample string with semi colon delimiters
    MyString = "john@myco.com;jane@myco.com;bill@myco.com;james@myco.com"
    
    'Use Split function to divide up the component parts of the string
    MyArray = Split(MyString, ";")
    
    'Clear the worksheet
    ActiveSheet.UsedRange.Clear
    
    'iterate through the array
    For N = 0 To UBound(MyArray)
        'Place each email address into the first column of the worksheet
        Range("A" & N + 1).Value = MyArray(N)
    Next N
End Sub

Alternatively, we can use the Transpose Function to output the array into a worksheet:

Sub CopyToRange()
    'Create variables
    Dim MyArray() As String, MyString As String
    
    'Sample string with space delimiters
    MyString = "One,Two,Three,Four,Five,Six"
    
    'Use Split function to divide up the component parts of the string
    MyArray = Split(MyString, ",")
    
    'Copy the array into the worksheet
    Range("A1:A" & UBound(MyArray) + 1).Value = WorksheetFunction.Transpose(MyArray)
End Sub

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

  1. 02-03-2015, 09:05 AM


    #1

    mitko007 is offline


    Registered User


    String to Range — VBA

    I have a string in a cell such as $A$1:$A$50 (range address as string)

    i want to use this string and convert it to a range and find the max value in it.

    Can someone provide some help on this issue. Thanks


  2. 02-03-2015, 09:20 AM


    #2

    Re: String to Range — VBA

    Please help by:

    Marking threads as closed once your issue is resolved. How? The Thread Tools at the top
    Any reputation (*) points appreciated. Not just by me, but by all those helping, so if you found someone’s input useful, please take a second to click the * at the bottom left to let them know

    There are 10 kinds of people in this world… those who understand binary, and those who don’t.


  3. 02-03-2015, 09:23 AM


    #3

    mitko007 is offline


    Registered User


    Re: String to Range — VBA

    thanks mate, i’ll give it a try. I also managed to get a solution with the INDIRECT worksheet function.


  4. 02-03-2015, 09:26 AM


    #4

    Re: String to Range — VBA


INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Contact US

Thanks. We have received your request and will respond promptly.

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!

  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It’s Free!

*Tek-Tips’s functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

VBA Excel Convert a range from string to integer

VBA Excel Convert a range from string to integer

(OP)

1 Sep 05 08:15

Hi Good people. My numbers are being stored as text in a range of cells. I want to be able to convert them to integers via VBA code so far I have this:

For Each C In Selection
Selection.TextToColumns Destination:=Range(Selection), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
        Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
        :=Array(1, 1), TrailingMinusNumbers:=True
Next

This comes up with an Run-Time error ‘1004’:
Method ‘Range’ of object’_Global failed.

I want to be able to code for an unknown range (what ever the user selects). I was thinking aout maybe using CInt( ), but I would still have the problem of referencing the selected range.

Any suggestions? Thanks DAVE

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Join Tek-Tips® Today!

Join your peers on the Internet’s largest technical computer professional community.
It’s easy to join and it’s free.

Here’s Why Members Love Tek-Tips Forums:

  • Tek-Tips ForumsTalk To Other Members
  • Notification Of Responses To Questions
  • Favorite Forums One Click Access
  • Keyword Search Of All Posts, And More…

Register now while it’s still free!

Already a member? Close this window and log in.

Join Us             Close

# Ways to refer to a single cell

The simplest way to refer to a single cell on the current Excel worksheet is simply to enclose the A1 form of its reference in square brackets:

Note that square brackets are just convenient syntactic sugar (opens new window) for the Evaluate method of the Application object, so technically, this is identical to the following code:

You could also call the Cells method which takes a row and a column and returns a cell reference.

Remember that whenever you pass a row and a column to Excel from VBA, the row is always first, followed by the column, which is confusing because it is the opposite of the common A1 notation where the column appears first.

In both of these examples, we did not specify a worksheet, so Excel will use the active sheet (the sheet that is in front in the user interface). You can specify the active sheet explicitly:

Or you can provide the name of a particular sheet:

There are a wide variety of methods that can be used to get from one range to another. For example, the Rows method can be used to get to the individual rows of any range, and the Cells method can be used to get to individual cells of a row or column, so the following code refers to cell C1:

# Creating a Range

A Range (opens new window) cannot be created or populated the same way a string would:

It is considered best practice to qualify your references (opens new window), so from now on we will use the same approach here.
More about Creating Object Variables (e.g. Range) on MSDN (opens new window) . More about Set Statement on MSDN (opens new window).

There are different ways to create the same Range:

Note in the example that Cells(2, 1) is equivalent to Range(«A2»). This is because Cells returns a Range object.
Some sources: Chip Pearson-Cells Within Ranges (opens new window); MSDN-Range Object (opens new window); John Walkenback-Referring To Ranges In Your VBA Code (opens new window).

Also note that in any instance where a number is used in the declaration of the range, and the number itself is outside of quotation marks, such as Range(«A» & 2), you can swap that number for a variable that contains an integer/long. For example:

If you are using double loops, Cells is better:

# Offset Property

  • Offset(Rows, Columns) — The operator used to statically reference another point from the current cell. Often used in loops. It should be understood that positive numbers in the rows section moves right, wheres as negatives move left. With the columns section positives move down and negatives move up.

i.e

This code selects B2, puts a new string there, then moves that string back to A1 afterwards clearing out B2.

# Saving a reference to a cell in a variable

To save a reference to a cell in a variable, you must use the Set syntax, for example:

later…

Why is the Set keyword required? Set tells Visual Basic that the value on the right hand side of the = is meant to be an object.

# How to Transpose Ranges (Horizontal to Vertical & vice versa)

Note: Copy/PasteSpecial also has a Paste Transpose option which updates the transposed cells’ formulas as well.

# Syntax

  • Set — The operator used to set a reference to an object, such as a Range
  • For Each — The operator used to loop through every item in a collection

Note that the variable names r, cell and others can be named however you like but should be named appropriately so the code is easier to understand for you and others.

“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.

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.)

vba ranges video

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

  1. Read from a cell.
  2. Write to a cell.
  3. 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.

code name 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

  1. Cells returns a range of one cell only.
  2. 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)

 
ImmediateWindow

 
ImmediateSampeText

 
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.

 
VBA Offset

 
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.

VBA CurrentRegion

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

  1. Range returns a range of cells
  2. Cells returns one cells only
  3. You can read from one cell to another
  4. You can read from a range of cells to another range of cells.
  5. You can read values from cells to variables and vice versa.
  6. You can read values from ranges to arrays and vice versa
  7. You can use a For Each or For loop to run through every cell in a range.
  8. 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.)

Like this post? Please share to your friends:
  • Vba programming excel to word
  • Vba for word forms
  • Vba for word and excel
  • Vba for word 2013
  • Vba for word 2010