0

Currently i am able to import text files into excel using vba. But, i can't figure out how to copy the data from the text file into current workbook. Everytime i run the program, it opens a new workbook for every text file.

Sub CopyData()

    Dim fileDialog As fileDialog
    Dim strPathFile As String
    Dim strFileName As String
    Dim strPath As String
    Dim dialogTitle As String
    Dim wbSource As Workbook
    Dim rngToCopy As Range
    Dim rngRow As Range
    Dim rngDestin As Range
    Dim lngRowsCopied As Long


    dialogTitle = "Navigate to and select required file."
    Set fileDialog = Application.fileDialog(msoFileDialogFilePicker)
    With fileDialog
        .InitialFileName = "C:\Users\User\Documents"
        .AllowMultiSelect = True
        .Filters.Clear
        .Title = dialogTitle



        If .Show = False Then
            MsgBox "File not selected to import. Process Terminated"
            Exit Sub
        End If
        strPathFile = .SelectedItems(1)
    End With

     Workbooks.OpenText Filename:=strPathFile, _
        Origin:=xlWindows, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
        xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _
        Comma:=False, Space:=False, Other:=False, FieldInfo:=Array(1, 1), _
        TrailingMinusNumbers:=True




    Set fileDialog = Nothing
    Set rngRow = Nothing
    Set rngToCopy = Nothing
    Set wbSource = Nothing
    Set rngDestin = Nothing

    MsgBox "The data is copied"

End Sub
Community
  • 1
  • 1
Subhaac
  • 437
  • 12
  • 26

1 Answers1

0

Although Siddart provided you a link, you can also try below. i just added a few fixes to somehow help you get you what you want.

Edit2:

Sub CopyData()

Dim fileDia As FileDialog
Dim i As Integer
Dim done As Boolean
Dim strpathfile As String, filename As String

'--> initialize variables here
i = 1
done = False

Set fileDia = Application.FileDialog(msoFileDialogFilePicker)
With fileDia
    .InitialFileName = "C:\Users\" & Environ$("username") & "\Documents"
    .AllowMultiSelect = True
    .Filters.Clear
    .title = "Navigate to and select required file."
    If .Show = False Then
        MsgBox "File not selected to import. Process Terminated"
        Exit Sub
    End If
    '--> you need to iterate to the files selected, open and dump each in your current wb
    Do While Not done
        On Error Resume Next
        strpathfile = .SelectedItems(i)
        On Error GoTo 0

        If strpathfile = "" Then
            done = True
        Else
            filename = Mid(strpathfile, InStrRev(strpathfile, "\") + 1, Len(strpathfile) - (InStrRev(strpathfile, "\") + 4))
            '--> I added this because the maximum lengh of sheet name is 31.
            '--> It will throw error if you exceed 31 characters.
            If Len(filename) > 31 Then filename = Left(filename, 26)
            '--> use the transfer sub here, take note of the new ByVal argument
            Transfer strpathfile, filename
            'Debug.Print filename
            strpathfile = ""
            i = i + 1
        End If
    Loop
End With

Set fileDia = Nothing

End Sub

Supporting Sub (Edit2):

Sub Transfer(mySource As String, wsName As String)

Dim wbSource As Workbook
Dim wsDestin As Worksheet
Dim lrow As Long

Set wsDestin = ThisWorkbook.Sheets.Add(, ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)) 'Add the worksheet at the end
On Error Resume Next
wsDestin.Name = wsName 'set the name
On Error GoTo 0

Application.DisplayAlerts = False
If InStr(wsDestin.Name, "Sheet") <> 0 Then wsDestin.Delete: Exit Sub

Workbooks.OpenText filename:=mySource, _
    Origin:=xlWindows, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
    xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _
    Comma:=False, Space:=False, Other:=False, FieldInfo:=Array(1, 1), _
    TrailingMinusNumbers:=True

Set wbSource = ActiveWorkbook

With wsDestin
    '--> get the last row of your destination sheet, i assumed you want Column A
    lrow = .Range("A" & Rows.Count).End(xlUp).Row
    '--> not comfortable in UsedRange but this should work, else define your range.
    '--> i can't because, i can't see your actual data
    wbSource.Sheets(1).UsedRange.Copy .Range("A" & lrow).Offset(1, 0)
    wbSource.Close False
End With
Application.DisplayAlerts = True

End Sub

Hope this is somewhat close to what you need.
Already tested and is working fine.
But i'm not sure if you agree on how i put a unique identifier to your sheet name.
I've chosen sheets current count.
Change that part to what ever you want.
This now ignores the file if it is already loaded.

L42
  • 19,427
  • 11
  • 44
  • 68
  • which line gives the error? :) i'll test it on my end as well. – L42 Jan 10 '14 at 03:05
  • This Line, Workbooks.OpenText FileName:=mySource, _ Origin:=xlWindows, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _ xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _ Comma:=False, Space:=False, Other:=False, FieldInfo:=Array(1, 1), _ TrailingMinusNumbers:=True – Subhaac Jan 10 '14 at 03:10
  • see updated code :). It should work now. The problem is `Transfer` still executes even if `strpathfile = ""` already on the last loop. To handle this, we just modify the if statement so execute `Transfer` if `strpathfile` in not `""`. – L42 Jan 10 '14 at 03:17
  • It works, is it possible to create new worksheets for each text file that is imported? – Subhaac Jan 10 '14 at 03:28
  • yes of course :). What would be the basis of the name of the `Worksheets`? – L42 Jan 10 '14 at 03:33
  • The name of the worksheet should be the name of the text file – Subhaac Jan 10 '14 at 03:37
  • ok, i'll update my post. but give me an hour? i'm on break :D – L42 Jan 10 '14 at 03:52
  • Sure, no problem. Maraming salamat po! :D – Subhaac Jan 10 '14 at 03:53
  • oh pinoy. same here :D hope we got all your concerns covered. – L42 Jan 10 '14 at 04:59
  • The line, wsDestin.Name = wsName Gives Run-time error '1004': Cannot rename a sheet to the same name as another sheet, a referenced object library or a workbook referenced by Visual Basic. This happens most of the time when selecting multiple files – Subhaac Jan 10 '14 at 07:34
  • ah, that means you are loading text files with the same file name. if the length of the filename is not yet maxed, you can include a handler when you set the `wsDestin.Name`. Can you give me example file names that were repeated? but if it's confidential don't bother :) – L42 Jan 10 '14 at 07:44
  • The file name are simply numbers. For example 175719, 185423 – Subhaac Jan 10 '14 at 08:02
  • are you sure no filename is repeated? We can add a handler though. See my update. – L42 Jan 10 '14 at 08:34
  • No filename is repeated. I use a couple of the same files when testing the program. When i run the program again and select the same files, this error pops up. – Subhaac Jan 10 '14 at 08:44
  • LOL... @_@ hehe of course it will throw up error. As the prompt explained, you cannot name sheet with the same name. Nonetheless, i've provided you a solution. :) – L42 Jan 10 '14 at 08:48
  • This creates a new worksheet if i select a file that i've already selected before. Is it possible to delete the existing worksheet with the same name, and creating this new one with the same name as the deleted one? I'm so sorry for troubling you so much :(. I'm new to vba and am struggling learning it – Subhaac Jan 10 '14 at 09:03
  • so you don't want to repeat reloading the same file? not a problem. But be sure to learn from here. :) let me modify the code a bit. – L42 Jan 10 '14 at 09:29
  • I am learning alot from here, especially from you lol. Thanks alot for your help :) – Subhaac Jan 13 '14 at 04:43
  • Hello again! How can I modify this code to loop for only 50 times. In other words, the program must only allow the user to select 50 files. – Subhaac Feb 05 '14 at 07:55
  • not sure but try this: `If .SelectedItems.Count > 50 Then Msgbox "Selected Files Exceeded the limit": Exit Sub` – L42 Feb 05 '14 at 08:05
  • This works. I have around 500 files in one folder. I want the user to select only 50 files and process them using this program in batches. If the user selects more thn 50 files, i want the program to only take the first 50 files selected, and store the name of the 51th file to a variable. I can make use of this variable to notify the user the first file for the next batch. – Subhaac Feb 05 '14 at 08:33