Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to open and read a xls file within VBA code? 2

Status
Not open for further replies.

rock31

Programmer
Jul 18, 2004
38
US
Dear there,
I need to open a xls file within my VBA code such as

sub readxlsdata()
' open xx.xls
' read 4 cells from sheet 1

end sub

I wonder, I should I do this?

Thanks alot.
R
 
R,

Here is some code to do what you want:
Code:
Sub readxlsdata()
Dim wkbData As Workbook
Dim a, b, c, d

  Set wkbData = Workbooks.Open("C:\FilePath\xx.xls")
  With wkbData.Worksheets("Sheet1")
    a = .Range("A1").Value
    b = .Range("A2").Value
    c = .Range("A3").Value
    d = .Range("A4").Value
  End With
  
End Sub
Of course, the ranges are just examples and you'll replace these with your own. Also note, the C:\FilePath\ should be replaced with the actual directory path to your xls file. I did not include error handling but you should, especially when opening files.


Regards,
Mike
 
It's always best to test if the file is already open or not, which we can do with a simple function ...

Code:
Sub TTtest()
    Dim wb As Workbook, blnWasOpen As Boolean
    Dim a, b, c, d
    If IsWbOpen("Book1.xls") Then
        Set wb = Workbooks("Book1.xls")
        blnWasOpen = True
    Else
        Set wb = Workbooks.Open("C:\YourPathHere\Book1.xls")
        blnWasOpen = False
    End If
    With wb.Sheets("Sheet1")
        a = .Range("A1").Value
        b = .Range("A2").Value
        c = .Range("A3").Value
        d = .Range("A4").Value
    End With
    If Not blnWasOpen Then wb.Close savechanges:=True
End Sub

Function IsWbOpen(wbName As String) As Boolean
    On Error Resume Next
    IsWbOpen = Len(Workbooks(wbName).Name)
End Function

HTH

-----------
Regards,
Zack Barresse
 
Thank you firefytr, and rmikesmith.
What you posted are of great help to me.
R.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top