Here’s an example of VBA code that reads data from an Excel worksheet and displays it in a message box:
Sub ReadDataFromExcel() Dim wb As Workbook Dim ws As Worksheet Dim rng As Range Dim cell As Range Dim data As String ' Open the workbook Set wb = Workbooks.Open("C:\Path\to\your\Workbook.xlsx") ' Set the worksheet to read from Set ws = wb.Worksheets("Sheet1") ' Set the range to read Set rng = ws.Range("A1:B10") ' Modify the range as per your requirements ' Read the data from each cell in the range For Each cell In rng data = data & cell.Value & vbNewLine Next cell ' Close the workbook wb.Close ' Display the data in a message box MsgBox data End Sub
In this code, you need to modify the file path in the Workbooks.Open
statement to point to the actual location of your Excel workbook. Also, modify the worksheet name and range as per your requirements.
When you run this code, it will open the workbook, read the data from the specified range, store it in the data
variable, close the workbook, and then display the data in a message box.
Note: Make sure to enable the “Microsoft Excel Object Library” in the VBA editor before running this code. You can do this by going to “Tools” > “References” and checking the box next to “Microsoft Excel Object Library.”