从txt文件导入到Excel工作簿

时间:2015-06-30 11:44:14

标签: excel excel-vba excel-2010 vba

我正在尝试将一些信息从文本文件导入到Excel中的工作表中,但它的作用是我复制所有信息并将其粘贴,它不会将它们复制到不同的单元格中。我的代码如下。我该怎么办?

    Sheets(1).Activate
  Sheets(1).Range(B2).Activate //(File name)    

    fileIn = ActiveCell.Value
       Workbooks.OpenText Filename:=Filename, Origin:=xlWindows, _
        startRow:=0, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
        ConsecutiveDelimiter:=True, Tab:=True, Semicolon:=False, Comma:=False, _
        Space:=True, Other:=False, FieldInfo:=Array(Array(2, 1), Array(3, 1), Array(4, 1)), _ 
    DecimalSeparator:=".", ThousandsSeparator:=",", _
        TrailingMinusNumbers:=True
        fileOpen = True


  ActiveSheet.Cells.Select
  Selection.NumberFormat = "0"
  Selection.Copy
  Workbooks(thisFile).Activate
  ActiveSheet.Range("A1").Select
  ActiveSheet.Paste

  Application.DisplayAlerts = False
  Windows("test.cfm").Activate 
  ActiveWindow.Close
  fileOpen = False
  Application.DisplayAlerts = True
  Sheets(2).Activate
  Rows("2:2").Select
  Selection.Delete

1 个答案:

答案 0 :(得分:1)

尝试使用正确的分隔符导入数据,下面使用逗号作为分隔符,但您可以通过将值更改为true来更改:

Sub importData()
Dim wb As Workbook
Dim ws As Worksheet

Set wb = ActiveWorkbook '<- Your workbook
Set ws = wb.Sheets("Sheet1") '<- Your worksheet where you want to add data

    With ActiveSheet.QueryTables.Add(Connection:="TEXT;C:\yourfolder\yourfile.txt", Destination:=ws.Range("A1")) '<- Starting range where you want to paste
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .Refresh BackgroundQuery:=False
    End With
End Sub