To read a cell value in Excel VBA, you can use the Range object along with the Value property. Here’s an example:
Sub ReadCellValue()
Dim wb As Workbook
Dim ws As Worksheet
Dim cellValue As Variant
' Open the workbook
Set wb = Workbooks.Open("C:\YourFilePath\YourWorkbook.xlsx")
' Set the worksheet you want to work with
Set ws = wb.Worksheets("Sheet1")
' Read the value of cell A1
cellValue = ws.Range("A1").Value
' Display the cell value in a message box
MsgBox "The value of cell A1 is: " & cellValue
' Close the workbook without saving changes
wb.Close SaveChanges:=False
End Sub
In this example, we first open the specified workbook using the Open method of the Workbooks object. Then, we set the worksheet we want to work with using the Worksheets property of the Workbook object.
To read the value of a cell, we use the Range property of the Worksheet object. In this case, we read the value of cell A1 by providing the cell address as a parameter.
The value of the cell is stored in the cellValue variable, which is then displayed in a message box using the MsgBox function.
Finally, we close the workbook without saving any changes by calling the Close method of the Workbook object and passing False as the SaveChanges parameter.