简体   繁体   English

将数据从文本文件复制到Excel工作簿

[英]Copying data from a text file to an Excel workbook

Currently i am able to import text files into excel using vba. 目前,我能够使用vba将文本文件导入excel。 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

Although Siddart provided you a link, you can also try below. 尽管Siddart为您提供了链接,但是您也可以尝试以下操作。 i just added a few fixes to somehow help you get you what you want. 我只是添加了一些修复程序,以某种方式帮助您获得所需的内容。

Edit2: 编辑2:

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): 辅助子(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. 现在,该文件将被忽略(如果已加载)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM