Get values from excel cell to vba

In this Article

  • Set Cell Value
    • Range.Value & Cells.Value
    • Set Multiple Cells’ Values at Once
    • Set Cell Value – Text
    • Set Cell Value – Variable
  • Get Cell Value
    • Get ActiveCell Value
    • Assign Cell Value to Variable
  • Other Cell Value Examples
    • Copy Cell Value
    • Compare Cell Values

This tutorial will teach you how to interact with Cell Values using VBA.

Set Cell Value

To set a Cell Value, use the Value property of the Range or Cells object.

Range.Value & Cells.Value

There are two ways to reference cell(s) in VBA:

  • Range Object – Range(“A2”).Value
  • Cells Object – Cells(2,1).Value

The Range object allows you to reference a cell using the standard “A1” notation.

This will set the range A2’s value = 1:

Range("A2").Value = 1

The Cells object allows you to reference a cell by it’s row number and column number.

This will set range A2’s value = 1:

Cells(2,1).Value = 1

Notice that you enter the row number first:

Cells(Row_num, Col_num)

Set Multiple Cells’ Values at Once

Instead of referencing a single cell, you can reference a range of cells and change all of the cell values at once:

Range("A2:A5").Value = 1

Set Cell Value – Text

In the above examples, we set the cell value equal to a number (1).  Instead, you can set the cell value equal to a string of text.  In VBA, all text must be surrounded by quotations:

Range("A2").Value = "Text"

If you don’t surround the text with quotations, VBA will think you referencing a variable…

Set Cell Value – Variable

You can also set a cell value equal to a variable

Dim strText as String
strText = "String of Text"

Range("A2").Value = strText

Get Cell Value

You can get cell values using the same Value property that we used above.

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!

automacro

Learn More

Get ActiveCell Value

To get the ActiveCell value and display it in a message box:

MsgBox ActiveCell.Value

Assign Cell Value to Variable

To get a cell value and assign it to a variable:

Dim var as Variant

var = Range("A1").Value

Here we used a variable of type Variant. Variant variables can accept any type of values.  Instead, you could use a String variable type:

Dim var as String

var = Range("A1").Value

A String variable type will accept numerical values, but it will store the numbers as text.

If you know your cell value will be numerical, you could use a Double variable type (Double variables can store decimal values):

Dim var as Double

var = Range("A1").Value

However, if you attempt to store a cell value containing text in a double variable, you will receive an type mismatch error:

get cell value assign variable

Other Cell Value Examples

VBA Programming | Code Generator does work for you!

Copy Cell Value

It’s easy to set a cell value equal to another cell value (or “Copy” a cell value):

Range("A1").Value = Range("B1").Value

You can even do this with ranges of cells (the ranges must be the same size):

Range("A1:A5").Value = Range("B1:B5").Value

Compare Cell Values

You can compare cell values using the standard comparison operators.

Test if cell values are equal:

MsgBox Range("A1").Value = Range("B1").Value

Will return TRUE if cell values are equal. Otherwise FALSE.

You can also create an If Statement to compare cell values:

If Range("A1").Value > Range("B1").Value Then

  Range("C1").Value = "Greater Than"

Elseif Range("A1").Value = Range("B1").Value Then

  Range("C1").Value = "Equal"

Else

  Range("C1").Value = "Less Than"

End If

You can compare text in the same way (Remember that VBA is Case Sensitive)

A cell is an individual cell and is also a part of a range. Technically, there are two methods to interact with a cell in VBA: the range method and the cell method. We can use the range method like range(“A2”). The value will give us the value of the A2 cell, or we can use the cell method as cells(2,1). The value will also give us the value of A2 cells.

Be it Excel or VBA, we all need to work with cells because it will store all the data in cells. So, it all boils down to how well we know about cells in VBA. So, if cells are such a crucial part of the VBA, then it is important to understand them well. So, if you are a starter regarding VBA cells, this article will guide you on how to get cell values in Excel VBA in detail.

First, we can reference or work with cells in VBA in two ways: using CELLS propertyCells are cells of the worksheet, and in VBA, when we refer to cells as a range property, we refer to the same cells. In VBA concepts, cells are also the same, no different from normal excel cells.read more and RANGE object. Of course, why CELLS is a property and why RANGE is an object is a different analogy. Later in the article, we will get to that point.

Table of contents
  • Get Cell Value with Excel VBA
    • Examples of getting Cell Value in Excel VBA
      • Example #1 – Using RANGE or CELLS Property
      • Example #2 – Get Value from Cell in Excel VBA
      • Example #3 – Get Value from One Cell to Another Cell
    • Things to Remember
    • Recommended Articles

Get-Cell-Value-in-VBA

Examples of getting Cell Value in Excel VBA

Below are the examples of getting cell values in Excel VBA.

You can download this VBA Get Cell Value Excel Template here – VBA Get Cell Value Excel Template

Example #1 – Using RANGE or CELLS Property

In cell A1 we have a value of “India.”

VBA Get cell value Example 1

We can reference this cell with a CELLS property or RANGE object. Let us see both of them in detail.

Using Range Property

First, start the macro procedure.

Code:

Sub Get_Cell_Value()

End Sub

VBA Get cell value Example 1-1

Now open the RANGE object.

Code:

Sub Get_Cell_Value()

Range(

End Sub

VBA Get cell value Example 1-2

The first argument of this object is “Cell1,” which is the cell we are referring to. In this case, it is cell A1, so we need to supply the cell address in double quotes for the RANGE object.

Code:

Sub Get_Cell_Value()

Range("A1")

End Sub

VBA Get cell value Example 1-3

Since only one cell refers to other parameters is irrelevant, close the bracket and put a dot to see the IntelliSense list.

VBA Get cell value Example 1-4

As you can see above, the moment we put a dot, we can see all the available IntelliSense lists of properties and methods of range objects.

Since we are selecting the cell, we need to choose the “SELECT” method from the IntelliSense list.

Code:

Sub Get_Cell_Value()

Range("A1").Select

End Sub

VBA Get cell value Example 1-5

Now, select the cell other than A1 and run the code.

vba get cell value example 1

It does not matter which cell you select when you run the code. It has chosen the mentioned cell, i.e., the A1 cell.

Using Cells Property

Similarly, we use the CELLS property now.

Code:

Sub Get_Cell_Value()

Range("A1").Select
Cells(

End Sub

Example 1-6

Unlike the RANGE object, we could directly supply the cell address. However, using this CELLS property, we cannot do that.

The first argument of this property is “Row Index,” i.e., which row we are referring to. Since we are selecting cell A1 we are referring to the first row, so mention 1.

Example 1-7

The next argument is the “Column Index,” i.e., which column we refer to. For example, the A1 cell column is the first column, so enter 1.

Example 1-8

Our code reads CELLS (1, 1) i.e. first row first column = A1.

Now, put a dot and see whether you get to see the IntelliSense list or not.

VBA Get cell value Example 1-9

We cannot see any IntelliSense list with CELLS properties, so we must be sure what we are writing. Enter “Select” as the method.

Code:

Sub Get_Cell_Value()

Range("A1").Select
Cells(1, 1).Select

End Sub

VBA Get cell value Example 1-10

This will also select cell A1.

Example #2 – Get Value from Cell in Excel VBA

Selecting is the first thing we have learned. Now, we will see how to get value from cells. Before we select the cell, we need to define the variable to store the value from the cell.

Code:

Sub Get_Cell_Value1()

Dim CellValue As String

End Sub

Example 2

Now, mention the cell address using either the RANGE object or the CELLS property. Since you are a beginner, use the RANGE object only because we can see the IntelliSense list with the RANGE object.

For the defined variable, put an equal sign and mention the cell address.

Code:

Sub Get_Cell_Value1()

Dim CellValue As String

CellValue = Range("A1")

End Sub

Example 2-1

Once again, put a dot to see the IntelliSense list.

Intellisense list Example 2-2

From the VBA IntelliSense list, choose the “Value” property to get the value from the mentioned cell.

Code:

Sub Get_Cell_Value1()

Dim CellValue As String

CellValue = Range("A1").Value

End Sub

Example 2-3

Now, the variable “CellValue” holds the value from cell A1. Show this variable value in the message box in VBA.

Code:

Sub Get_Cell_Value1()

Dim CellValue As String

CellValue = Range("A1").Value

MsgBox CellValue

End Sub

Example 2-4

Run the code and see the result in a message box.

vba get cell value example 2

Since there is a value of “INDIA” in cell A1, the same thing also appeared in the message box. Like this, we can get the value of the cell by the VBA valueIn VBA, the value property is usually used alongside the range method to assign a value to a range. It’s a VBA built-in expression that we can use with other functions.read more of the cell.

Example #3 – Get Value from One Cell to Another Cell

We know how to get value from the cell using VBA. Now, the question is how to insert a value into the cell. Let us take the same example only. For cell A1, we need to insert the value of “INDIA,” which we can do from the code below.

Code:

Sub Get_Cell_Value2()

Range("A1").Value = "INDIA"

End Sub

VBA Get cell value Example 3

It will insert the value of “INDIA” to cell A1. Similarly, we can write the code below to get value from one cell to another.

Code:

Sub Get_Cell_Value2()

Range("A5").Value = Range("A1").Value

End Sub

VBA Get cell value Example 3-1

Let me explain the code to you.

For cell A5, we need the value from the cell A1 value; that’s all this code says. So, this will get the value from cell A1 to A5 using VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.

VBA Get cell value Example 3-2

Things to Remember

  • Inserting value to cells and getting value from the cell requires the VBA “VALUE” property to be used.
  • We can select only one cell using the CELLS property but use the RANGE object. Likewise, we can select multiple cells.

Recommended Articles

This article has been a guide to Get Cell Value in Excel VBA. Here, we discuss the examples of getting cell values using a range of cell properties in Excel VBA and a downloadable Excel template. Below you can find some useful Excel VBA articles: –

  • VBA Variable Range
  • Split String into Array in VBA
  • Range Cells in VBA
  • Active Cell in VBA
Skip to content

Read or Get Data from Worksheet Cell to VBA in Excel

Home » Excel VBA » Read or Get Data from Worksheet Cell to VBA in Excel

  • Reading data from Cell Range

Description:

Its one of my first questions when I started learning EXcel VBA, How to Read or Get Data from Worksheet Cell to VBA? To automate any thing in excel, first we need to read the data in Worksheet and based on that we can execute the next steps.

Read or Get Data from Worksheet Cell to VBA in Excel – Solution(s):

It is very simple to read the data from Excel to VBA. We can use Cell or Range Object to refer a Worksheet Cell.

Get Data from Worksheet Cell – An Example of using Cell Object

The following example will show you how to read or get the data from Worksheet Cell using Cell Object.

Example Codes

In this example I am reading the data from first Cell of the worksheet.

Sub sbGetCellData()

MsgBox Cells(1, 1)
'Here the first value is Row Value and the second one is column value 
'Cells(1, 1) means first row first column
End Sub

In this example I am reading the data from first row and fourth column of the worksheet.

Sub sbGetCellData1()

MsgBox Cells(1, 4)

End Sub

Here is sample picture, which helps you to understand this concepts. Any Row or Column number start with 1 and You have to specify Cell(RowNumber,ColumnNumber) to read the data from a Cell of the Worksheet.

Reading data from Cells

Get Data from Worksheet Cell – An Example of using Range Object

The following example will show you how to read or get the data from Worksheet Cell or Range using Range Object.

Example Codes

In this example I am reading the data from first Cell of the worksheet.

Sub sbGetCellData2()

MsgBox Range("A1")
'Here you have to specify the Cell Name which you want to read - A is the Column and 1 is the Row

End Sub

Here is sample picture, which helps you to understand this concepts. If you select any cell in the worksheet, you can see the name of that cell in the Name Box.

Reading data from Cell Range

Get Data from Worksheet Cell – Specifying the Parent Objects

When you are reading using Cell or Range object, it will read the data from Active Sheet. If you want to read the data from another sheet, you have to mention the sheet name while reading the data.

The below example is reading the data from Range A5 of Sheet2:

Sub sbGetCellData2()

MsgBox Sheets("Sheet2").Range("A5")
'Here the left side part is sheets to refer and the right side part is the range to read.

End Sub

In the same way you can mention the workbook name, if you are reading the data from different workbooks.

Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

Related Posts

    • Description:
  • Read or Get Data from Worksheet Cell to VBA in Excel – Solution(s):
    • Get Data from Worksheet Cell – An Example of using Cell Object
    • Get Data from Worksheet Cell – An Example of using Range Object
    • Get Data from Worksheet Cell – Specifying the Parent Objects

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

70 Comments

  1. Magesh
    February 18, 2014 at 3:02 PM — Reply

    I want continue number from A1 to A10 but only while am typed in B1 to B10 like
    A1 1 Magesh
    A2 2 Kumar
    A3 3 Sathish
    A4
    A5 4 Raja
    A6 5 Ram
    A7 6 Raju
    A8 7 Samy

    A9 8 Prabu
    A10 9 Raja

    A11 10 Magesh

    how to put this number alternately in Ms Excel 2007 using VBA.

    with regards,
    Magesh

  2. PNRao
    February 18, 2014 at 11:27 PM — Reply

    Hi Magesh,

    You can use the following code. Paste this code in your worksheet module:


    Private Sub Worksheet_Change(ByVal Target As Range)
    'print if B is not empty and A is empty
    If Cells(Target.Row, 2) <> " And Cells(Target.Row, 1) = " Then
    Cells(Target.Row, 1) = Target.Row
    End If


    End Sub

    Thanks-PNRao!

  3. praveen
    August 7, 2014 at 12:55 PM — Reply

    Hi,

    This information is really helpful; I have one question:
    1. I want to read the data from cell(i.e sheet2-Row1)
    2. It has to read Unique record from Row1
    3. It has to give count in sheet1 as summary based on criteria

    Regards
    Praveen

  4. PNRao
    August 17, 2014 at 11:25 AM — Reply

    Hi Praveen,

    You can use Worksheet functions to perform this task. You can use CountIf or SumIf functions to create summaries based on criteria.

    For Example:
    cnt = Application.WorksheetFunction.CountIf(Range(“A1:A10”), “Your Criteria”)

    Thanks-PNRao!

  5. fakru
    October 3, 2014 at 3:35 PM — Reply

    how to read data from a any random selection

  6. PNRao
    October 3, 2014 at 8:49 PM — Reply

    You can use Selection.Value.

  7. jai
    October 10, 2014 at 12:10 PM — Reply

    I want to read all the rows from a cell in one sheet and compare with all the rows in other cell in another sheet and each rows should be compared and it is a string value present in the rows..please help me out in this.

  8. Tsuna
    November 27, 2014 at 3:34 PM — Reply

    Can somebody help me with this gentlemen,

    I have a User form with 5 textboxes, I want to put the value of a cell in the textboxes but the value in each textboxes are from different sheets. Can anyone help me with this situation.

    Thank you in advance.

  9. PNRao
    November 29, 2014 at 7:35 PM — Reply

    Hi Tsuna,
    The following code will get the values from 5 different sheets to 5 different text boxes:

    TextBox1.Value=Sheets(“Sheet1”).Range(“A5”)
    TextBox2.Value=Sheets(“Sheet2”).Range(“A5”)
    TextBox3.Value=Sheets(“Sheet3”).Range(“A5”)
    TextBox4.Value=Sheets(“Sheet4”).Range(“A5”)
    TextBox5.Value=Sheets(“Sheet5”).Range(“A5”)

    Thanks
    PNRao!

  10. suraj
    December 10, 2014 at 12:51 AM — Reply

    Need help. I want to create a new sheet in an existing workbook. But the name should be that i enter in cell B2 and then click on a create button. ‘actually i want for multiple values but will use the same logic. Anyone please???

  11. sima
    December 27, 2014 at 7:48 PM — Reply

    hi
    i want to create a bottom when pressing, the data of the current sheet transfer to my matrix in my program,is it possible?
    how?
    thanks in advance.

  12. Shareef
    January 4, 2015 at 9:56 PM — Reply

    Hi,
    The VBA codes regarding macros ex: copytopaste macro it works sometimes n some times it shows error user type not defined. Pls help me out. M getting irritation because berceuse of this.

  13. PNRao
    January 6, 2015 at 7:57 PM — Reply

    Hi Shareef,

    Requesting you to paste the code which is not working.

    Thanks-PNRao!

  14. Manooj
    January 20, 2015 at 2:25 PM — Reply

    Hi,
    can any one help me with the below senario

    I hav 3 sheets in the excel and i need to take a particular value from sheet one and subtract it with a particular value from sheet 2 and this shouls be displayed in sheet 3.

    Thanks,
    Manooj

  15. PNRao
    January 23, 2015 at 10:47 AM — Reply

    Assuming you want to subtract A2 of Sheet1 from A2 of Sheet2 and print at A2 of Sheet3:

    Sheets("Sheet3").Range("A2")= Sheets("Sheet2").Range("A2") - Sheets("Sheet1").Range("A2")
    

    Thanks-PNRao!

  16. N. Panchal
    March 19, 2015 at 11:48 AM — Reply

    Hi,
    Consider below scenario…
    In Row 1 Starting from B1, C1, D1…I have entered date in dd/mm/yyyy
    In Column 1, Starting from A2, A3, A4, I have empolyee Code… like EMP1, EMP2 etc..
    Now, from third party application I want to access this sheet using VBA and based on current date(From first Row) and EMP code (From First Column), I want to read corresponding value in that Cell, meeting corresponding.row and column.
    Required EMP code can be entered from my application to a variable in VBA.
    Anyone can me help out with this..

  17. Sarika
    April 16, 2015 at 10:47 AM — Reply

    Hi,

    I am looking to write a script in excel to get the data from one sheet to another sheet in different way.

    eg: input

    emp m1 m2 m3 m4
    abc 1 2 3 4
    def 5 6 7 8
    ghi 9 10 11 12

    ouput should be like the below :

    emp
    abc 1 m1
    abc 2 m2
    abc 3 m3
    abc 4 m4
    def 5 m1
    def 6 m2
    def 7 m3
    def 8 m4

    like wise there are “n” number of emps..

    Please help.

    Thanks
    Sarika

  18. sowmi
    April 17, 2015 at 7:46 AM — Reply

    it is wonderful. I am having one problem. We are having 600 rows and 12 column worksheet. Can I have a code for locating a particular value (key value) in the sheet and to displa ay the values of the row.

    The same as our friend Panchal requires

  19. Bhamila
    April 20, 2015 at 2:24 PM — Reply

    Can you Help me to write a code to arrange the letters like below.

    Lets say if my input is 01234567890 – then the result has to be 34567890.012 and vice versa.

    But the program has to read the input from excel sheet automatically if I entered 1000 value in A column.

  20. Haider
    April 29, 2015 at 12:31 AM — Reply

    Hi please help me with this one:

    The code below should read all value from cell P1:P4 and implement it in an autofilter…Thanks for your help in advance

    Sub c1()
    Sheets(“Master”).Select
    MsgB Range(“P1”)
    MsgB1 Range(“P2”)
    MsgB2 Range(“P3”)
    MsgB3 Range(“P4”)

    Dim i As Long
    For i = 2 To 13
    With Sheets(i).Activate
    ActiveSheet.Range(“$Y$2:$Y$2999”).AutoFilter Field:=1, Criteria1:=Array(MsgB, MsgB1, MsgB2, MsgB3)
    Range(“A1”).Select
    On Error Resume Next
    End With
    Next i
    End Sub

  21. SADDAM HUSAIN
    May 15, 2015 at 12:36 PM — Reply

    i want to open a browser windows in excel sheet . how will i open??

  22. tanvi
    May 19, 2015 at 4:17 PM — Reply

    Hi,

    I have below requirement:

    Sheet1: Two cols
    Col1 Col2
    A 1
    B 2
    C 3

    Sheet2: Two Cols
    Col1 Col2
    A 2
    D 3
    C 4

    Read Col1 -Lets say A from sheet 1, (loop thru each row in Col1), search the first value of Col1 which is A in sheet2 and get its corresponding Number which is 2 and write this in sheet1 in Col3.

    Sheet1: 3 cols
    Col1 Col2 Col3
    A 1 2
    B 2 NA
    C 3 4

    Can Anyone please help with this question.

    Thanks so much!

  23. PNRao
    May 22, 2015 at 9:13 PM — Reply

    Hi Tanvir,
    We can use two for loops to do this, but using worksheet function will be simpler. Here is the macro to Search For A String And Get The Corresponding Value From Other Sheet.

    Sub sbSearchForAStringAndGetTheCorrespondingValueFromOtherSheet()
    lRowSheet1 = Sheets("Sheet1").Range("A100000").End(xlUp).Row ' Please refer the code finding the last row in our 100+ Example
    
    For i = 1 To lRowSheet1
    If Sheets("Sheet1").Range("A" & i) <> " Then
        If Not IsError(Application.WorksheetFunction.Match(Sheets("Sheet1").Range("A" & i), Sheets("Sheet2").Range("A:A"), 0)) Then
            Sheets("Sheet1").Range("C" & i) = Sheets("Sheet2").Range("C" & Application.WorksheetFunction.Match(Sheets("Sheet1").Range("A" & i), Sheets("Sheet2").Range("A:A"), 0))
        End If
    End If
    Next
    End Sub
    

    Thanks-PNRao!

  24. Rajesh B
    June 11, 2015 at 5:31 PM — Reply

    Hi Friends, Please me in this, I have a requirement ike if we have one Excel file which we have list of computers name

    http://www.google.com
    http://www.Google.hk
    http://www.Google.co.in

    I wants to cut this www for all the rows and I have to put it in another excel sheet . How to do this with VB script. Please help me , thanks in advance.

  25. PNRao
    June 12, 2015 at 6:10 PM — Reply

    Hi Rajesh,

    Here is the code which will help you to solve your requirement.

    Sub MoveAndChangedData()

    ‘Here moving original data from Sheet1(Source Sheet Name) to Sheet2(Destination Sheet Name)
    ‘You can change the range(“A1:D10”) according to your requirement
    Sheets(“Sheet15”).Range(“A1:D10”).Copy Destination:=Sheets(“Sheet16”).Range(“A1”)

    ‘Replacing “WWW” with blanks in the destination sheet
    With Sheets(“Sheet16”)
    .Activate
    .Range(“A1:D10″).Replace What:=”WWW”, Replacement:=”, LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
    End With

    End Sub

    Thanks-Valli!

  26. Rajesh B
    June 15, 2015 at 4:33 PM — Reply

    But Friend, It does not work throws error and i corrected the uotes which is in different format in the excel when i tried copy paste from here, after corrected its throws run time error like Run time error : 9 subscript out of range like that,.

  27. bujar
    June 27, 2015 at 10:19 AM — Reply

    Hello everyone,

    I have an excel master sheet that is created for every customer filename will change each time, the workbook layout is the same. I would like a macro to import some of the information from the master sheet, I have 3 sheets in the workbook, from each sheet I would need to copy few cell data (any range would be fine, i will change that to fit by needs) to a new workbook. I would like the macro button also to move down each time the new data is imported. New Workbook data range paste to A2:D2, next A3:D3 and so on. Below is the code i have so far.

    Thank you in advance,

    This is the Code I have.

    VB:
    Sub Foo()
    Dim vFile As Variant
    Dim wbCopyTo As Workbook
    Dim wsCopyTo As Worksheet
    Dim wbCopyFrom As Workbook
    Dim wsCopyFrom As Worksheet

    Set wbCopyTo = ActiveWorkbook
    Set wsCopyTo = ActiveSheet
    ‘————————————————————-
    ‘Open file with data to be copied

    vFile = Application.GetOpenFilename(“Excel Files (*.xl*),” & _
    “*.xl*”, 1, “Select Excel File”, “Open”, False)

    ‘If Cancel then Exit
    If TypeName(vFile) = “Boolean” Then
    Exit Sub
    Else
    Set wbCopyFrom = Workbooks.Open(vFile)
    Set wsCopyFrom = wbCopyFrom.Worksheets(1)
    End If

    ‘————————————————————–
    ‘Copy Range
    wsCopyFrom.Range(“b5”).Copy
    wsCopyTo.Range(“a2”).PasteSpecial Paste:=xlPasteValues, _
    Operation:=xlNone, SkipBlanks:=False, Transpose:=False

    ‘Close file that was opened
    wbCopyFrom.Close SaveChanges:=False

    End Sub

  28. JOTS
    July 7, 2015 at 9:20 PM — Reply

    hi

    I have the names of all the workbooks which are listed on a worksheet called”filelist” saved in a workbook called “Read property and transaction data with macro to be run 070715.xlsm”. I need to get the workbook to open for all the the names listed in filelist worksheet and go to the tab called “GL Transactions” and retrieve a value from call AB12 and save it in the workbook “Read property and transaction data with macro to be run 070715.xlsm” under a tab called GL Total. How can I record a macro for this?

  29. Deepan
    August 24, 2015 at 2:31 PM — Reply

    How to retrieve a particular percentage of value(ex:get only 20% of data from sheet i.e out of 20 users,we need only 4 users name to be displayed) from excel sheet using macro?

  30. PNRao
    August 25, 2015 at 12:37 AM — Reply

    Hi,
    Find the last row and loop through the 20% of last row to fetch only 20% of the data.

    Example:

    Sub sbGetOnly20PercentOfData()
    Set SourceWb = Workbooks.Open("C://....") ' your file path
    
    SourceWbLastRow = 500 'See our example in 100+ popular macro list to find last rows dynamically in different scenaios
    rows20percent = CInt(SourceWbLastRow * 0.2)
    For i = 1 To rows20percent
    Sheets("DestinationSheet").Range("B" & i) = SourceWb.Sheets("SheetName").Range("A" & i)
    Next i
    
    End Sub
    

    Thanks-PNRao!

  31. Ajay
    October 7, 2015 at 3:21 PM — Reply

    Hi PNRao Sir,
    In the above example by you i am able to find only 1 data in excel sheet, i need to find many data in excel sheet so how will be do this can you please help me this
    If there are many data in excel sheet in need to find all data from Sheet In Particular TextBox

  32. Ajay
    October 31, 2015 at 12:22 PM — Reply

    It’s a lot more easier if you just write a formula for this instead of VBA code.

  33. Pkaran
    December 14, 2015 at 7:02 PM — Reply

    I have a excel file contains in the cell AI one, A2 two, A3 three,… I want to copy the value in another excel one in the sheet1 cell A1, two in the sheet2 cell A1, three in the sheet3 cell A1,…

  34. Younis
    January 12, 2016 at 1:01 PM — Reply

    I would like the macro button which is importe new data from sheet1 and paste on sheet2 A2:D3 but when new data inserted in sheet1 the range of sheet2 will be A3:D3 and so on.

  35. Younis
    January 20, 2016 at 12:45 PM — Reply

    I would like the macro button which is importe new data from sheet1 and paste on sheet2 A2:D3 but when new data inserted in sheet1 the range of sheet2 will be A3:D3 and so on.

  36. AlexC
    February 13, 2016 at 3:44 AM — Reply

    I want to select and print the worksheets in a workbook whose cell, (I22), contains a value greater than one (1).

    Thank you

  37. Ahmed
    March 20, 2016 at 1:47 PM — Reply

    i have excel sheet need to create sub menus , when select value its creates sub menu , when select value its generate another menu with formulas & conditions

  38. Ahmed
    March 20, 2016 at 1:53 PM — Reply

    Hi Developer
    i have excel sheet with formulas & conditions , i need to generate menus and sub menus , when select value its generate sub menus with conditions & formulas , i need to generate 10 menus based on cell value

    could you please help me ?

  39. nht
    March 23, 2016 at 10:21 AM — Reply

    i have problem: i have sheet “abc”, in sheet “abc” have colum A
    A1=”NG”
    A2=”Ok”
    A3=”NG”
    .
    .
    A7=”OK”
    .
    .
    I want count num “NG” in sheet A
    Plz Help me!!

  40. fab
    March 28, 2016 at 12:47 PM — Reply

    Sub main()
    Dim Newsheet As Worksheet
    Dim val As Double
    Dim Firstrow As Integer
    Dim Lastrow As Integer
    Dim totscore1 As Integer
    Dim i As Integer, j As Integer
    Sheets(“sheet1”).Select
    Range(“D2”).Select
    Firstrow = ActiveCell.row
    Selection.End(xlDown).Select
    Lastrow = ActiveCell.row

    totscore1 = Lastrow – Firstrow
    Sheets(“sheet1”).Select
    Range(“B2”).Select
    Firstrow = ActiveCell.row
    Selection.End(xlDown).Select
    Lastrow = ActiveCell.row

    Range(“F2”).Select
    For i = 0 To totscore1
    val = Cells(2, 3).Value – Cells(2, 4).Value
    ActiveCell.Value = val
    ActiveCell.Offset(1, 0).Select
    Next i
    End Sub

    Hi,
    The code is working only for the cells D2-B2. And the same value getting printed. I want the results down the column (Relative referencing).. D3-B3, D4-B4… so on. Please help

  41. Mark
    April 25, 2016 at 7:51 PM — Reply

    Hi Vali,

    You have provided quite insightful answers to all questions posed, please help me with mine:
    This is the rudimentary format for my excel:

    Name Place Gender Date occupation
    Arthur UK Male 16-4-78 Carpenter
    Mason
    Plumber
    Brad USA Male 5-10-80 Teacher
    Charlie Poland Male 13-8-69 Painter
    Singer
    Editor

    I’m trying to export this to a text file the result of which should look like this:

    Arthur UK
    Gender: Male
    Date: 16-4-78
    Occupation: Carpenter, Mason, Plumber

    Brad USA
    Gender: Male
    Date: 5-10-80
    Occupation: Teacher

    Charlie Poland
    Gender: Male
    Date: 13-8-69
    Occupation: Painter, Singer, Editor.

    have searched high and low, but in vain.

    The actual excel on which I’m working consists of 11 Columns, and have to deal with 300 to 350 rows at a time, which is a cumbersome task.

    Please help me with this.

  42. Archan Pagedar
    May 4, 2016 at 3:02 PM — Reply

    Hi nht,

    You can use formula “COUNTIF” for this.

  43. Rutger
    May 6, 2016 at 7:02 PM — Reply

    Hi, I want to add data from cells to an inputbox, do you have any clue on how to do that?
    thanks in advance!

    Rutger

  44. Deepak
    May 30, 2016 at 5:08 PM — Reply

    One Excel File (Table 1) containing Roll Nos. of candidates with other details like name, address, contact No., Email Id etc. for 2000 candidates and other Excel File (Table 2) containing only Roll Nos. of 200 candidates which are same as in Table 1 so I want to add other column details in Table 2 (only for 200 candidates) by retrieving records from Table 1 by searching Candidates Roll Nos. from Table No. 2.

    How it can be possible in Excel.

  45. Spyrijus
    June 10, 2016 at 12:31 AM — Reply

    Ok. So this problem is getting on my nerves for some time now. I made damage calculator using macros. Works pretty good. Now I want to add temporary hit points into account.
    Let’s say it looks like this:

    DMG TotalDMG TempHP HP
    2 3 7 24

    So, basicaly, I need to deplete TempHP first and with every dmg calculation to see if there is any TempHP left. So with every calculation I need to check the value of TempHP cell and DMG cell, then do TempHP – DMG (7-2) and the result should be new TempHP value (5). And when DMG is bigger than TempHP do the following: HP – (DMG – TempHP) and set TempHP to 0.

    Thanks in advance.

  46. Awanish
    August 16, 2016 at 11:56 AM — Reply

    Hello Expert

    I need to read value from column A excl sheet and export those value in txt file .

    Thanks in advance

  47. raja
    September 28, 2016 at 7:30 PM — Reply

    Hi,

    I want to select the data and month from the Date in cell(a1)(containing formula) and file 2016-06-07 ABCD should be opened using that date and month.

    Thanks

  48. Sohan
    November 18, 2016 at 1:18 PM — Reply

    I want a vba,
    I want to copy a cell’s value to another cell, but the cell on which, the value will be pasted, that cell’s number will be directed from another cell.
    Example: I want to copy value from ‘A1’ to a specific cell, and that specific cell’s number is specified on cell ‘B1’. [Note: value of ‘B1’ changes time to time according to formula]

    Please help me how can i do this ! Thank you…..

  49. Durai
    November 20, 2016 at 3:45 PM — Reply

    Dear Sir,

    I have some ComboBox – 8No’s and TextBox -40No’s in Sheet1 and our employee details (Emp.ID, Name, Date of Birth, Email, Contact Numbers) in Sheet2. I need to display employee id in Combobox 1 to 8 and when i select anyone employee id in ComboBox then his all details wants to display other Testboxes in Sheet1 as per below. But (Sr.No) not in Sheet2 database. Anyway i need to display when i select second Combobox, then Sr.No wants to display number-2 automatically. Kindly anyone give a solution to solve my query.

    Sr.No Emp. ID Name Date of Birth Email Contact No.
    1 1201 AAAAAAAA1 12/12/1980 dfs 1111111111
    2 1202 AAAAAAAA2 12/13/1980 dfs 1111111112
    3 1203 AAAAAAAA3 12/14/1980 dfs 1111111113
    4 1204 AAAAAAAA4 12/15/1980 dfs 1111111114
    5 1205 AAAAAAAA5 12/16/1980 dfs 1111111115
    6 1206 AAAAAAAA6 12/17/1980 dfs 1111111116
    7 1207 AAAAAAAA7 12/18/1980 dfs 1111111117
    8 1208 AAAAAAAA8 12/19/1980 dfs 1111111118

  50. Sasi
    November 20, 2016 at 5:58 PM — Reply

    Hi,

    i have an excel workbook which will be update frequently by inserting new worksheet. I want to get the value of specific cell in each sheets and send to one particular sheet to draw the graph once i insert new worksheet. Are there any VBA codes to send the cell value to specific sheet by clicking button?. Please help

  51. Mike
    January 10, 2017 at 6:24 AM — Reply

    Hi, this is wonderful platform and thank you all for yours comments! I’m pretty new in VBA and I’m finding this very helpful. Supposing I have excel file that has huge informations capture in it and these informations could be actions, time the action was done, number of actions performed for several users and are all ranged columns per user. How should write a script to extract this data based on those that user performed with <3 minutes, compute totals number of actions done by all user in specific time slot, categories the number of activities done in range of <2,3-4, 4< time difference. I will be very delighted.

  52. Haivus
    February 3, 2017 at 9:46 PM — Reply

    Hi,
    I have 3 different excel sheets which contain my client reviews with respect to Date as header followed respective dates in 1st column and 2nd column contains reviews as header followed by reviews. .
    so in all files i have same dates for eg: date : 23.06.2016 will have minimum of 30 reviews in each sheets, so wen i combine its taking too much time to open one file and filter and copy vice versa.
    Help me out with VBA coding so that i can pull out those datas easily into my master file with respective to dates.am having terrible n doing in this.

    thanks
    Haivus

  53. Arash
    June 6, 2017 at 11:21 AM — Reply

    Dear All how can I get the value in spread sheet (for example day and month) and use it as reference value to plot the point in VBA?
    Can you please explain it??

  54. YRUYIM
    August 17, 2017 at 12:28 AM — Reply

    Hi Everyone,

    I am trying to genrate text file from Excel via VBA and successful.

    My requiremet is to read data from multiple excell sheets write into text file, I can raead data from sheet1 of excel howver unable to read or move function from sheet1 to sheet2 or sheet3 to get data and write in text file,

    Can anyone help me pleas.

  55. Venus
    August 19, 2017 at 9:35 PM — Reply

    Hi,
    I am trying a scenario in which I have a Mini Invoice and my requirement is to save the data of the invoice and need to retrieve the saved data based on Invoice Number. I request to help me in this scenario giving the desired code.
    Thanks in advance.

  56. yash
    August 31, 2017 at 3:40 PM — Reply

    I have an excel database. I want a person’s all data by using only his / her mobile no. Is it possible by using VBA programming or other programming?

  57. PNRao
    September 1, 2017 at 11:41 PM — Reply

    Yes, Please let us know data structure. So that we can help you.

  58. Kundan
    November 27, 2017 at 9:55 PM — Reply

    Hi there,

    How to read a file stored in excel sheet through vba. I have a file path in cell A1 through A10. How to read each files contents and base64 encode it to store it in a string.

    Thanks!
    Kundan

  59. Roberto
    January 20, 2018 at 11:52 PM — Reply

    Hello, I have Category in column A and number of teams in column B and I already can create automatically worksheets with the names on column A, but now I want to paste on each new worksheet the data corresponding to the number of teams in column B.

    I already named the ranges so whenever I have e.g. 6 on column B , I just need to select data range _6 and paste it on A1 on the new worksheet.

    Can you tell me how to code this?

    Thanks in advance!

  60. Colin
    January 30, 2018 at 4:10 AM — Reply

    Hi
    I have a column of dates from Jan 1 to dec31 2017. The adjoining cell has a value in it
    I am setting targets and need to pull a certain dates value to the target sheet. Is it possible to do this
    Thanks

  61. Tresna Budiman
    June 5, 2018 at 7:45 AM — Reply

    Hi Master,
    Please let me know how to call the sub i made as :

    Sub Sumbycolorto(range_data As Range, ByVal range_tosum As Range, ByVal range2_tosum As Range, ByVal range_toset As Range, criteria As Range)
    Dim datax As Range
    Dim xcolor As Long
    Dim isi As Long
    xcolor = criteria.Interior.ColorIndex

    For Each datax In range_data
    isi = Cells(datax.Row, range_tosum.Column) + Cells(datax.Row, range2_tosum.Column)
    If datax.Interior.ColorIndex = xcolor Then
    Cells(datax.Row, range_toset.Column) = range_tosum.datax.Row + range2_tosum.datax.Row
    End If
    Next datax
    End Sub

    Sub Run_click()
    ‘ How to call ? Sumbycolorto ???
    End Sub

  62. PNRao
    June 14, 2018 at 10:12 AM — Reply

    Sub Run_click()
    ‘You can use Call statement and enter the inputs for parameters: range_data,range_tosum,range2_tosum,range_toset,criteria
    Call Sumbycolorto(range_data,range_tosum,range2_tosum,range_toset,criteria)
    End Sub

  63. Naem
    July 3, 2018 at 12:13 PM — Reply

    Can any one show me how to write a macro which reads values from a sheet with two columns consisting of dates and numerical values and calculates slope from these values but writes value of slope and date when slope changed from positive to negative and visa versa and ignore all values and not write only the date and slope at slope change only.
    Your input is appreciated.
    Naem

  64. Emil
    October 2, 2018 at 5:47 PM — Reply

    Hello, I have a lots of cells with this function: PrintFile (xxxyyyyssssqqqq.***)
    How can I run those functions within a dynamic range in vba?
    Basically, how can I run a function if it’s written as text in a cell?
    Thank you a lot!

  65. Vikramaditya Chouhan
    May 10, 2019 at 10:07 PM — Reply

    I have name of company in Column one with entries Employees name, salary, phone number in next column.
    The name of the company in first column repeats.

    I dont want the name of the company again and again. Only other entries like Employees Name, salary and phone number in new sheet.
    The Company name should appear once, rest all cells for same company must remain empty.

    Please suggest.

  66. Christopher Allyn Jenkins
    June 1, 2019 at 8:21 AM — Reply

    To anyone out there, I am stuck. I have created a button in Excel, I want to attach a Macro to this that adds up a series of numbers to make a growing total; “A1″+ “A2” – “A3” = Total
    So that if I change A1, A2, A3 it would give me the old total plus the sum of the new A1,A2,A3
    I have no clue what the code would look like please help!

  67. Rupesh
    December 1, 2019 at 8:36 PM — Reply

    Dim strCycle As String, i As Integer, trgSheet As String, sht As Worksheet
    With Sheets(“Run”)
    i = 2
    For Each sht In Sheets
    If sht.Name “Run” Then
    sht.Delete
    End If
    Next

    Do While True
    strCycle = .Cells(i, 1)
    If Len(Trim(strCycle)) = 0 Then Exit Do
    If strCycle = “All” Then
    trgSheet = “All_Summary”
    LoadDetail srcJIRAFile, “select LEFT([Test Summary],INSTR([Test Summary],’_’)-1) as EPIC_ID, x.* ” & _
    “from [Sheet1$] x WHERE Step=’Step1′”, trgSheet
    Else
    trgSheet = strCycle & “_Summary”
    LoadDetail srcJIRAFile, “select LEFT([Test Summary],INSTR([Test Summary],’_’)-1) as EPIC_ID, x.* ” & _
    “from [Sheet1$] x WHERE Step=’Step1′ and CycleName in (‘” & strCycle & “‘)”, trgSheet
    End If
    ThisWorkbook.Save

    LoadDetail ThisWorkbook.FullName, “select x.* from [” & trgSheet & “$] x,(SELECT [Test Summary], MAX(date+time) as dt” & _
    ” FROM [” & trgSheet & “$] group by [Test Summary]) t where ” & _
    ” x.[Test Summary]=t.[Test Summary] and (x.date+x.time)=t.dt”, strCycle & “_Snap”

    If strCycle “All” Then

    LoadDetail ThisWorkbook.FullName, “TRANSFORM COUNT(*) select EPIC_ID ” & _
    “FROM (Select Status,EPIC_ID from [” & strCycle & “_Snap$] UNION ALL ” & _
    “Select ‘Total’ as Status,EPIC_ID from [” & strCycle & “_Snap$]) group by EPIC_ID PIVOT Status”, strCycle & “_Status”
    End If
    If strCycle = “All” Then
    LoadDetail ThisWorkbook.FullName, “TRANSFORM COUNT(*) select CycleName ” & _
    “FROM (Select Status,CycleName from [” & strCycle & “_Snap$] UNION ALL ” & _
    “Select ‘Total’ as Status,CycleName from [” & strCycle & “_Snap$]) group by CycleName PIVOT Status”, strCycle & “_Status”
    End If

    i = i + 1
    Loop

    End With

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True

  68. Chirag Vadara
    June 5, 2020 at 10:57 AM — Reply

    Hello,
    I want to call value from a cell of excel in my VBA code how to do it. Plus i have some other query, i want to get the resulting values of my code in excel back. How it can be done

  69. Kumar S
    October 21, 2020 at 2:42 PM — Reply

    Hi – I am totally new to excel macro. I give below my macro. i would like to write the macro in one file and execute the same many times on the same day based on some criteria.

    My data has City name, date of transaction and other data spread over a few columns .

    1. I would like to select one file where the all transaction details are available. (Say AllData.xlsx).
    2. City Name will be received as Input at Macro as variable

    3. Need to select and open this file and read the contents row by row and write to another file -(Output File) (this file name to be generated into a variable like – OutputFileName = City Name + “Transactions Till ” + Yesterday Date + “.xlsx”. This file need to be created inside macro with the name assigned.

    4. The data read in AllData should be one row in full (or column by column as you recommend) and based on the first column (city name) matching with City Name received as input.

    5. If matching need to write on Output file one entire row.
    6. Read Next Row from AllData and if matching write to Output file
    7. Above process to be repeated till Last Record of AllData File.

    I tried but not getting correct code. Request you to give me the code and help me asap.

    Kumar S

  70. Hart
    December 16, 2020 at 2:05 AM — Reply

    Hi, I have excel sheet where i record quantity of our fresh products for our market , i need to set up VBA code to auto sent my manager email when quantity is on certain amount . Eg. A1 – PRODUCT DESCRIPTION, A2 – ARTICLE NUMBER, A3 – QUANTITY,
    B1 – BANANA, B2 – 52465, B3 – 47
    C1 – ORANGE, C2 – 63351, C3 – 28
    D1 – PEARS, D2 – 85856, D3 – 14.

    I need VBA to sent email to my manager for all products that are below 30 units accompanied by product description and article number.

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

Go to Top

I’m trying to do what I think is something simple and looks right. What I’m trying to do is pull a value from a cell on a worksheet that is in the current workbook. However, every time I run the code I get the following error: Run-time error’g’: Subscript out of range. Below is the listed code that I’m using.

Damp_DL_Height = ThisWorkbook.Sheets("DampType").Cells(3, 3).Value

I’ve got the variable defined as Double. DampType is equal to the name of the sheet that I’m trying to pull the cell data from. Should I be using some other type of command to get the value?

Any help is appreciated.

Community's user avatar

asked Sep 4, 2015 at 18:37

Bob Amick's user avatar

3

Since DampType is a string variable, it doesn’t need quotation marks —

Damp_DL_Height = ThisWorkbook.Sheets(DampType).Cells(3, 3).Value

answered Sep 4, 2015 at 18:54

Raystafarian's user avatar

RaystafarianRaystafarian

2,8922 gold badges30 silver badges42 bronze badges

Содержание

  1. VBA Ranges — Getting and Setting Cell Values
  2. Getting Cell Values
  3. What happens if you use .Value on a set of cells?
  4. How do you get a single cell from a set of cells?
  5. The Range.Cells Function
  6. Setting Cell Values
  7. How do you set multiple cells’ values?
  8. Getting and Setting Cell Values from a Named Range or Table Name
  9. What’s next?
  10. Get Cell Value in Excel VBA
  11. Get Cell Value with Excel VBA
  12. Examples of getting Cell Value in Excel VBA
  13. Example #1 – Using RANGE or CELLS Property
  14. Example #2 – Get Value from Cell in Excel VBA
  15. Example #3 – Get Value from One Cell to Another Cell
  16. Things to Remember
  17. Recommended Articles

VBA Ranges — Getting and Setting Cell Values

In the previous post, we introduced the VBA Range object. This gave us the foundation of working with Ranges in VBA. In today’s post, I’d like to discuss how to get and set cell values through VBA. This will continue to build up our understanding of the VBA Range object and how to use it. There are several ways you can get and set cell values with VBA and I’ll do my best to cover all the necessities, but at the same time keeping it short and to the point. Let’s get started.

Getting Cell Values

To get a cell’s value in VBA, we need to refer to it with the Range object and then call the .Value property.

We’ll use the following spreadsheet for our example. It’s a simple table with some names in it.

To get the value from cell A2 you can use this code snippet:

This will take cell A2 and put it in the variable val . Then we print out the value in the Immediate Window (which the value in our example is Joseph ).

You can also set the range to a variable and access the value from that variable as well:

What happens if you use .Value on a set of cells?

Let’s change our previous code snippet to the following:

If you run this code, you will get an error stating that there is a type mismatch.

What’s going on here?

The problem is that when you work with a set of cells, .Value can only return a single value. So when we ask VBA to return .Value on our variable (which refers to multiple cells), the .Value property doesn’t know which cell we are referring to.

How do you get a single cell from a set of cells?

In order to use .Value to get a value from a cell, we need to refer to a single cell from the range of cells in our variable. The way we do that is with the Cells() VBA function.

The Range.Cells Function

The Cells() function is a way to take a range of cells and return a single cell from the set. Here is the function defined:

Parameter Type Definition
row_number Integer The row number from within the range that you want to refer to.
column_number Integer The column number from within the range that you want to refer to.

Take a look at the following code:

Here we took the range of A2:A5 and referred to row 1 column 1. Since the range variable cellRange refers to A2:A5 , the first row is row 2 and the first column is A .

When using the Cells() function, remember that row 1 and column 1 represent the top-left most cell within the range that the Cells() function is working on. If your range is A1:D5 , then Cells(1, 1) will refer to A1 , but if your range is B2:D6 , then Cells(1, 1) refers to B2 .

Ok, that covers getting cell values from range objects, now let’s discuss setting cell values with range objects.

Does this article help you? If so, please consider supporting me with a coffee ☕️

Setting Cell Values

In order to set a cell’s value, you can use the same .Value property when referring to a cell. In this example, we’ll take A2 ’s value and change it from Joseph to John :

First we set the variable cellRange to A2 . Then we said cellRange.Value = «John» which changes the variable’s .Value property. Remember, though, that the variable is a reference to cell A2 , so whatever you do to that variable, you also do to cell A2 in the worksheet. Finally, we output the value of A2 into the Immediate Window to see that it changed.

We can also see the value changed in the worksheet after we run this code:

How do you set multiple cells’ values?

Remember how I said that you can only read from one cell using .Value ? Well, when setting values, you can actually set multiple cells at one time by using .Value . Take a look at the following code:

If you ran this code, it would set all A2:A5 ’s cells to John :

Well, maybe you’d actually want to do this for some other scenarios, like when you want a bunch of cells to repeat a value.

Let’s take a real example for a second. Let’s say we have two columns, First Name and Last Name . We want to take the Last Name column and place its value after the First Name ’s value; essentially combining the values to make a single Name column.

Here’s our sample data:

Our task is to combine the first and last name columns and place the result in column A . How do we do that?

One solution is to loop through cells A2 through A5 and then set that cell’s value to its own value, plus a space, plus the last name of the cell right next to it.

Sounds easy enough, let’s code it up:

Let’s step through the code.

  • First, we create a variable called names . Then, we set that to range A2:A5 .
  • Next, we create a variable called cell . This is going to be a temporary variable that will change with each iteration of the loop.

Then, we create the loop. Here, we’re looping through the names range object and setting the current item to the cell variable. This means that each time we run through the loop, cell represents a single range object.

*The first time the loop is run, cell is set to A2 . Then, A3 , next A4 , and finally A5 . After that, there are no more cells to go through in the names variable, so the loop ends.

  • I’ll go over how to loop through ranges in a future post since this post is already long enough!

Now we’re ready to combine the first and last names. How we do that is with another Range function called Offset(_rows_, _columns_) . The idea with this function is that if you’re on a cell like A2 and you say cell.Offset(0, 1) what we’re really saying is “move over one column to the right”. This puts us on cell B2 . That’s how we’re able to get the last name in our example.

  • I’ll discuss how to use the Offset() function in more detail in a future post. Again, this post has gone on long enough.

Here are the results of the code after we run it:

From here, we could change the A1 cell to just Name and delete column B altogether.

Getting and Setting Cell Values from a Named Range or Table Name

One last thing I’d like to touch on is when you use the Range() function, you can use a named range or table name instead of a range like A2:A5 . In our first example, our data is in a table named Table1 . To refer to the data of the table, we could use the following:

And to refer to the entire table, we can leverage structured referencesВ like so:

This will return A1 ’s value “Name” since the table starts in A1 .

Also, if you’re new to Excel Tables, click here to learn more.

What’s next?

Honestly, there is so much to discuss with range objects in VBA. I’ll be touching on many more topics regarding ranges in VBA in upcoming posts such as:

  • Modifying cell colors
  • Finding cells by their text values
  • Filtering data
  • Getting the last row in a range (you need this more often than you think)

I’ll come back to this post and put links to these posts as I create them.

If you enjoyed this content, please share and subscribe!

Wow, you read the whole article! You know, people who make it this far are true learners. And clearly, you value learning. Would you like to learn more about Excel? Please consider supporting me by buying me a coffee (it takes a lot of coffee to write these articles!).

Written by Joseph who loves teaching about Excel.

Источник

Get Cell Value in Excel VBA

Get Cell Value with Excel VBA

A cell is an individual cell and is also a part of a range. Technically, there are two methods to interact with a cell in VBA: the range method and the cell method. We can use the range method like range(“A2”). The value will give us the value of the A2 cell, or we can use the cell method as cells(2,1). The value will also give us the value of A2 cells.

Be it Excel or VBA, we all need to work with cells because it will store all the data in cells. So, it all boils down to how well we know about cells in VBA. So, if cells are such a crucial part of the VBA, then it is important to understand them well. So, if you are a starter regarding VBA cells, this article will guide you on how to get cell values in Excel VBA in detail.

First, we can reference or work with cells in VBA in two ways: using CELLS property Using CELLS Property Cells are cells of the worksheet, and in VBA, when we refer to cells as a range property, we refer to the same cells. In VBA concepts, cells are also the same, no different from normal excel cells. read more and RANGE object. Of course, why CELLS is a property and why RANGE is an object is a different analogy. Later in the article, we will get to that point.

Table of contents

You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article Link to be Hyperlinked
For eg:
Source: Get Cell Value in Excel VBA (wallstreetmojo.com)

Examples of getting Cell Value in Excel VBA

Below are the examples of getting cell values in Excel VBA.

Example #1 – Using RANGE or CELLS Property

In cell A1 we have a value of “India.”

We can reference this cell with a CELLS property or RANGE object. Let us see both of them in detail.

Using Range Property

First, start the macro procedure.

Code:

Now open the RANGE object.

Code:

The first argument of this object is “Cell1,” which is the cell we are referring to. In this case, it is cell A1, so we need to supply the cell address in double quotes for the RANGE object.

Code:

Since only one cell refers to other parameters is irrelevant, close the bracket and put a dot to see the IntelliSense list.

As you can see above, the moment we put a dot, we can see all the available IntelliSense lists of properties and methods of range objects.

Since we are selecting the cell, we need to choose the “SELECT” method from the IntelliSense list.

Code:

Now, select the cell other than A1 and run the code.

It does not matter which cell you select when you run the code. It has chosen the mentioned cell, i.e., the A1 cell.

Using Cells Property

Similarly, we use the CELLS property now.

Code:

Unlike the RANGE object, we could directly supply the cell address. However, using this CELLS property, we cannot do that.

The first argument of this property is “Row Index,” i.e., which row we are referring to. Since we are selecting cell A1 we are referring to the first row, so mention 1.

The next argument is the “Column Index,” i.e., which column we refer to. For example, the A1 cell column is the first column, so enter 1.

Our code reads CELLS (1, 1) i.e. first row first column = A1.

Now, put a dot and see whether you get to see the IntelliSense list or not.

We cannot see any IntelliSense list with CELLS properties, so we must be sure what we are writing. Enter “Select” as the method.

Code:

This will also select cell A1.

Example #2 – Get Value from Cell in Excel VBA

Selecting is the first thing we have learned. Now, we will see how to get value from cells. Before we select the cell, we need to define the variable to store the value from the cell.

Code:

Now, mention the cell address using either the RANGE object or the CELLS property. Since you are a beginner, use the RANGE object only because we can see the IntelliSense list with the RANGE object.

For the defined variable, put an equal sign and mention the cell address.

Code:

Once again, put a dot to see the IntelliSense list.

From the VBA IntelliSense list, choose the “Value” property to get the value from the mentioned cell.

Code:

Now, the variable “CellValue” holds the value from cell A1. Show this variable value in the message box in VBA.

Code:

Run the code and see the result in a message box.

Since there is a value of “INDIA” in cell A1, the same thing also appeared in the message box. Like this, we can get the value of the cell by the VBA value VBA Value In VBA, the value property is usually used alongside the range method to assign a value to a range. It’s a VBA built-in expression that we can use with other functions. read more of the cell.

Example #3 – Get Value from One Cell to Another Cell

We know how to get value from the cell using VBA. Now, the question is how to insert a value into the cell. Let us take the same example only. For cell A1, we need to insert the value of “INDIA,” which we can do from the code below.

Code:

It will insert the value of “INDIA” to cell A1. Similarly, we can write the code below to get value from one cell to another.

Code:

Let me explain the code to you.

Things to Remember

  • Inserting value to cells and getting value from the cell requires the VBA “VALUE” property to be used.
  • We can select only one cell using the CELLS property but use the RANGE object. Likewise, we can select multiple cells.

Recommended Articles

This article has been a guide to Get Cell Value in Excel VBA. Here, we discuss the examples of getting cell values using a range of cell properties in Excel VBA and a downloadable Excel template. Below you can find some useful Excel VBA articles: –

Источник

Понравилась статья? Поделить с друзьями:
  • Get tongue round the word
  • Get to visual basic in excel
  • Get time on excel
  • Get tick in word
  • Get the word out means