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

时间:2014-01-09 01:29:52

标签: excel-vba excel-2007 vba excel

目前我可以使用vba将文本文件导入excel。但是,我无法弄清楚如何将文本文件中的数据复制到当前工作簿中。每次运行程序时,它都会为每个文本文件打开一个新的工作簿。

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

1 个答案:

答案 0 :(得分:0)

虽然Siddart为您提供了链接,但您也可以尝试下面的链接。 我刚刚添加了一些修复程序,以某种方式帮助您获得所需的内容。

<强> 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

支持子(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

希望这与您的需求有些接近 已经过测试,工作正常 但我不确定您是否同意我如何为您的工作表名称添加唯一标识符 我选择了床单当前计数 将该部分更改为您想要的任何内容 现在,如果文件已经加载,则忽略该文件。