Avatar of jay_waugh
jay_waugh
Flag for United Kingdom of Great Britain and Northern Ireland

asked on 

Copy data from Excel into MSAccess

I am trying to open a spreadsheet from MSAccess using VBA. I then want to select some cells on the spreadsheet to copy the data into an access table. At the moment I can't even get the code to select the cells on the spreadsheet to work. Can you help please?

Private Sub opwb()

Dim sPath As String
Dim sFile As String
Dim WorkbookToRead As String
Dim excelApp As Excel.Application
Dim wb As Excel.Workbook
Dim Flag As String
Dim strPath As String
Dim strAppFPSS As String
Dim strAppId As String
Dim fpHostnames As Variant
Dim strWorkSheetName As String
Dim hn As Range


strPath = "C:\temp\"
strAppFPSS = "Doc1"
strAppId = Mid(strAppFPSS, 1, InStr(1, strAppFPSS, " ") - 1)
strWorkBook = strPath & strAppFPSS & ".xlsx"
strWorkSheetName = "payments"
   
On Error Resume Next

Set excelApp = GetObject(, "Excel.Application")  'http://support.microsoft.com/kb/288902 - If Excel is not open, an error occurs and Err.Number > 0
                Flag = 1
If Err.Number <> 0 Then Set excelApp = CreateObject("Excel.Application") 'There is an error if Err.Number <> 0     Create Excel.Application

On Error GoTo Err_Handler
                Flag = 2

    With excelApp
        .Visible = True  'Excel becomes visible. Confirmed.
        Set wb = .Workbooks.Open(strWorkBook, ReadOnly:=True)
        wb.Sheets(8).Sheets(strWorkSheetName).Range("A2").Select
        Sheets(strWorkSheetName).Range(Selection, Selection.End(xlDown)).Select
               
    End With
             
               
    Set wb = Nothing
    Set excelApp = Nothing

Exit_Sub:
    Exit Sub

Err_Handler:
    Set wb = Nothing
    Set excelApp = Nothing
    MsgBox Err.Description
    MsgBox "An error occurred while in Private Sub OpenExcelWorkbook(), called from cmdOpenExcelWorkbook_Click() | Flag = " & Flag
    Resume Exit_Sub

End Sub
Microsoft AccessVBA

Avatar of undefined
Last Comment
John Tsioumpris

8/22/2022 - Mon