Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

Import xls file from a specific folder

0

Hello, I`d like to import an xls file from a specific folder into my current workbook. whenever I want to use my pathline, the code stops  but it works when I use open.file....Also, the code imports the selected file in a separate workbook, but I want it in the workbook that I`m currently working on but in a separate sheet so leave sheet 1 as is and start the process in sheet 2. here is my code (you can ignore the second half since its not related to my problem -  i think). TIA!!

Sub ImportCopySheetAndAddFormulas()
    Dim selectedFile As Variant
    Dim srcWorkbook As Workbook
    Dim srcWorksheet As Worksheet
    Dim copyWorksheet As Worksheet
    Dim timestampCell As Range
    Dim timestampRow As Long

    ' Allow the user to select the XLS file
    selectedFile = Application.GetOpenFilename("Excel Files (*.xls), *.xls")
    If selectedFile = "False" Then
        MsgBox "You did not select a file.", vbExclamation
        Exit Sub
    End If

    ' Import data from the XLS file
    Set srcWorkbook = Workbooks.Open(selectedFile)
    Set srcWorksheet = srcWorkbook.Sheets(1)


    ' Create a new sheet and copy the data to it in the same workbook
    Set copyWorksheet = srcWorkbook.Sheets.Add(After:=srcWorkbook.Sheets(srcWorkbook.Sheets.Count))
    srcWorksheet.UsedRange.Copy copyWorksheet.Range("A1")

    ' Find the row with the word "timestamp"
    On Error Resume Next
    Set timestampCell = copyWorksheet.Cells.Find(What:="timestamp", LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)
    On Error GoTo 0

    If timestampCell Is Nothing Then
        MsgBox "The word 'timestamp' was not found in the copied sheet.", vbExclamation
        Exit Sub
    Else
        timestampRow = timestampCell.Row
    End If

    ' Delete rows above the timestamp row
    If timestampRow > 1 Then
        copyWorksheet.Rows("1:" & timestampRow - 1).Delete Shift:=xlUp
    End If

    ' Delete all columns after the second column
    copyWorksheet.Columns("C:O").Delete Shift:=xlToRight

    ' Add the specified formulas
    copyWorksheet.Range("E1").Value = "Time"
    copyWorksheet.Range("F1").Value = "Average"
    copyWorksheet.Range("I1").Value = "Time"
    copyWorksheet.Range("J1").Value = "Average"
    copyWorksheet.Range("L1").Value = "10 min avg"
    copyWorksheet.Range("E2").Formula = "=AVERAGE(INDEX(A:A,1+60*(ROW()-ROW($E$2))):INDEX(A:A,60*(ROW()-ROW($E$2)+1)))"
    copyWorksheet.Range("F2").Formula = "=AVERAGE(INDEX(B:B,1+60*(ROW()-ROW($F$2))):INDEX(B:B,60*(ROW()-ROW($F$2)+1)))"
    copyWorksheet.Range("I2").Formula = "=OFFSET($E$2,(ROW(E1)-1)*10,0)"
    copyWorksheet.Range("J2").Formula = "=OFFSET($F$2,(ROW(F1)-1)*10,0)"
    copyWorksheet.Range("L3").Formula = "=AVERAGE(INDEX(F:F,1+10*(ROW()-ROW($L$3))):INDEX(F:F,10*(ROW()-ROW($L$3)+1)))"

     ' Format columns E and I to display time as HH:mm:ss AM/PM
    copyWorksheet.Columns("E:E").NumberFormat = "HH:mm AM/PM"
    copyWorksheet.Columns("I:I").NumberFormat = "HH:mm AM/PM"

    'Format columns F, J, L to 2 decimal places"
    copyWorksheet.Columns("F:F").NumberFormat = "0.00"
    copyWorksheet.Columns("J:J").NumberFormat = "0.00"
    copyWorksheet.Columns("L:L").NumberFormat = "0.00"

    'Adjust column A to autofill
    copyWorksheet.Columns("A").AutoFit

    MsgBox "Data imported from the selected XLS file. A copy is created in the same workbook with rows above 'timestamp' removed and the specified formulas added.", vbInformation
End Sub
Answer
Discuss

Answers

0
Selected Answer

Josue

To open a known (existing) file, you can use;

Set srcWorkbook = Workbooks.Open("E:\folder\subfolder\YourFile.xlsx")

but it will produce an error if you make a mistake in typing the full path and file name (including the extension), most likely Runtime Error 1004.

Revision 03 August 2023:

My previous answer is modified (in the light of your comments below and recently- attached two files), as follows:

In the attached revised file, I've made changes to your code (in bold below in the code) which:

  1. moves the ChDir line befoe it atteampts to launch the OpenFile dialog
  2. comments out  the On Error Resume Next and  ... GoTo 0 lines (which is meaningless without a line starting 0:)
  3. opens the user-selected file (if any) and copies its first sheet to two new sheets in your macro workbook (given your discussion point mentioned "two sheets in a new workbook"). First is "Full SoundPro data" and second "SoundPro Timestamp data"
  4. closes that file after the data copy then continues with your processing of the second new sheet (removing extraneous data etc.) but also...
  5. uses the With (object) / End With approach to save the dozen or so repeats of "copyWorksheet"

Here's the code, with key new comments following ###

Sub ImportCopySheetAndAddFormulas()
    Dim selectedFile As Variant
    Dim srcWorkbook As Workbook
    Dim srcWorksheet As Worksheet
    Dim copyWorksheet As Worksheet
    Dim timestampCell As Range
    Dim timestampRow As Long
    
    ' ### first change to desired folder
    ChDir "C:\Users\jcriollo\Documents"
    
    ' Allow the user to select the XLS file from that folder
    selectedFile = Application.GetOpenFilename("Excel Files (*.xls), *.xls")
     On Error GoTo ErrorMessage 'error message if not found path

'    ChDir "C:\Users\jcriollo\Documents"
    
    If selectedFile = "False" Then
        MsgBox "You did not select a file.", vbExclamation
        Exit Sub
ErrorMessage:
        MsgBox "Josue`s Folder not found - change File Path" 'change this as needed
        Exit Sub
    End If
    
    ' ### ========Import to THIS workbook
    ' ### Open the selected XLS file
    Set srcWorkbook = Workbooks.Open(selectedFile)
    Set srcWorksheet = srcWorkbook.Sheets(1)
    
    ' ### Create first new sheet in this workbook...
'    Set copyWorksheet = srcWorkbook.Sheets.Add(After:=srcWorkbook.Sheets(srcWorkbook.Sheets.Count))
    Set copyWorksheet = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
    copyWorksheet.Name = "Full SoundPro data"
    ' ### ...and copy the data to it from the opened workbook
    srcWorksheet.UsedRange.Copy copyWorksheet.Range("A1")
    
    ' ### Create a second new sheet in this workbook...
    Set copyWorksheet = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
    copyWorksheet.Name = "SoundPro Timestamp data"
    ' ### ...and copy the data to it from the opened workbook
    srcWorksheet.UsedRange.Copy copyWorksheet.Range("A1")
    
    ' ### Close that open workbook, without saving any changes
    srcWorkbook.Close SaveChanges:=False
    
    ' Find the row with the word "timestamp"
    On Error Resume Next
    Set timestampCell = copyWorksheet.Cells.Find(What:="timestamp", LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)
    'On Error GoTo 0
    
    If timestampCell Is Nothing Then
        MsgBox "The word 'timestamp' was not found in the copied sheet.", vbExclamation
        Exit Sub
    Else
        timestampRow = timestampCell.Row
    End If
    
    '### Use "With/ End With" construction to avoid repetition
    With copyWorksheet
        ' Delete rows above the timestamp row
        If timestampRow > 1 Then
            .Rows("1:" & timestampRow - 1).Delete Shift:=xlUp
        End If
        
        ' Delete all columns after the second column
        .Columns("C:O").Delete Shift:=xlToRight
        
        ' Add the specified formulas
        .Range("E1").Value = "Time"
        .Range("F1").Value = "Average"
        .Range("I1").Value = "Time"
        .Range("J1").Value = "Average"
        .Range("L1").Value = "10 min avg"
        .Range("E2").Formula = "=AVERAGE(INDEX(A:A,1+60*(ROW()-ROW($E$2))):INDEX(A:A,60*(ROW()-ROW($E$2)+1)))"
        .Range("F2").Formula = "=AVERAGE(INDEX(B:B,1+60*(ROW()-ROW($F$2))):INDEX(B:B,60*(ROW()-ROW($F$2)+1)))"
        .Range("I2").Formula = "=OFFSET($E$2,(ROW(E1)-1)*10,0)"
        .Range("J2").Formula = "=OFFSET($F$2,(ROW(F1)-1)*10,0)"
        .Range("L3").Formula = "=AVERAGE(INDEX(F:F,1+10*(ROW()-ROW($L$3))):INDEX(F:F,10*(ROW()-ROW($L$3)+1)))"
        
         ' Format columns E and I to display time as HH:mm:ss AM/PM
        .Columns("E:E").NumberFormat = "HH:mm AM/PM"
        .Columns("I:I").NumberFormat = "HH:mm AM/PM"
        
        'Format columns F, J, L to 2 decimal places"
        .Columns("F:F").NumberFormat = "0.00"
        .Columns("J:J").NumberFormat = "0.00"
        .Columns("L:L").NumberFormat = "0.00"
        
        'Adjust column A to autofill
        .Columns("A").AutoFit
    
    End With
    
    MsgBox "Data imported from the selected XLS file. A copy is created in the same workbook with rows above 'timestamp' removed and the specified formulas added.", vbInformation
End Sub

It seemed to import the data succerssfully from your Sample.xls file. You know how to avoid seeing the momentary opening and closing of that file, right?

I understand you're using .xls files (Excel97 format) since SoundPro exports to that but please note that they were superseded by .xlsx and xlsm (for macro-enabled) formats a long time ago..

Hope this fixes your problem (once you add the correct, full path). If so, please remember to mark this Answer as Selected.

Discuss

Discussion

Hi John, thank you for the help. For some reason your code doesn`t work on my end and I keep getting "end if" error and I can`t figure out what it is. Also, I added both workbooks that I`ll be using. One has the macro and the other contains the data (sample file). When I run my code, and it looks how I want it to look, but it opens a whole new workbook instead of creating two separate sheet in the "soundpro import" file. In addition, I`m only using the folder`s path instead of the file`s itself.  

On a side note, I`m using .xls simply because that`s how an old software that I`m saves the files as.

Thanks again for your time
josuec52 (rep: 4) Aug 2, '23 at 9:35 pm
Josue   Please see my revised Answer and file.   For future questions, please always attach files- it saves us guessing and having to rework our Answers.
John_Ru (rep: 6142) Aug 3, '23 at 11:46 am
Thanks a lot John! This worked perfectly.
josuec52 (rep: 4) Aug 4, '23 at 8:20 am
Glad that worked. Thanks for selecting my Answer, Josue.
John_Ru (rep: 6142) Aug 4, '23 at 8:49 am
Add to Discussion


Answer the Question

You must create an account to use the forum. Create an Account or Login