文本以excel文件输入提示

时间:2015-02-27 22:19:16

标签: excel excel-vba vba

我在创建excel时遇到问题。虽然我在使用记录功能之前创建了宏,但它不适用于此问题。任何帮助将不胜感激!

我必须将一堆分隔的文本文件导入到excel中,而向导非常有用,我希望自动完成整个过程。

我所做的是记录使用向导导入一个文件的过程。 当我重新运行录制的excel时,我得到以下错误: "运行时错误' 5': 无效的过程或调用参数"

当我调试时,它会在.CommandType = 0行中显示错误。

我有两个问题,如何摆脱错误信息,更重要的是,我如何更改代码,以便每次运行宏时都会弹出文件输入窗口? (我试图嵌入Application.GetOpenFilename()命令,但不幸的是没有成功)

非常感谢你的帮助!

干杯, dahlai

这是我的代码:

Sub ImportDataPeriod1()
'
' ImportDataPeriod1 Macro
'

'
With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;F:\pETMEOH100 15xx DHAP.txt", Destination:=Range("$A$3"))
        .CommandType = 0
        .Name = "pETMEOH100 15xx DHAP"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 850
        .TextFileStartRow = 37
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 1, 9, 1, 9, _
        9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 _
        , 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

1 个答案:

答案 0 :(得分:0)

第1期

我不明白.CommandType = 0行的存在。

我从未见过这个属性,因为我从未导入过有效的数据类型。根据我可以找到的文档:它对文本文件无效,0不是允许的值,它似乎已经过时,因为我只能在Excel 2003文档中找到它。我建议你删除这一行。

第2期

宏录制器不会录制一些命令;例如File Dialog命令。您必须键入自己的文件对话框命令。

第3期

"TEXT;F:\pETMEOH100 15xx DHAP.txt"只是一个字符串。宏记录器已将其创建为具有文件对话框值的文字。 TEXT;是强制性的,但字符串的其余部分可以以任何方便的方式创建。

<强>宏

你说你有一堆分隔的文本文件。我使用了文件对话框的AllowMultiSelect = True参数,因此可以一次选择多个文件。

我将所选文件移动到一个数组,这样我就可以在退出对话框后访问路径/文件名。

我为每个文件循环并且:

  • 查找或创建将导入文件的未使用工作表。
  • 通过丢弃路径和扩展名从路径/文件名中提取文件名。
  • 我使用文件名作为工作表的名称和查询
  • 导入文件。

小心我的导入参数。我的文本文件有不同的分隔符,使用UTF-7编码,只有5个字段。使用.Add.Name以外的参数。根据需要调整我的范围。

Option Explicit
Sub ImportFiles()

  Dim Found As Boolean
  Dim InxFile As Long
  Dim InxWsht As Long
  Dim NameFileCrnt As String
  Dim PathFile() As String
  Dim Pos As Long
  Dim WshtNew As Worksheet

  ' Open the file dialog
  With Application.FileDialog(msoFileDialogFilePicker)
    .AllowMultiSelect = True
    .Show

    If .SelectedItems.Count = 0 Then
      Call MsgBox("No file selected", vbOKOnly)
      Exit Sub
    End If

    ' Copy the name and path of every file selected by the user to array PathFile
    ReDim PathFile(1 To .SelectedItems.Count)
    For InxFile = 1 To .SelectedItems.Count
      PathFile(InxFile) = .SelectedItems(InxFile)
    Next

  End With

  For InxFile = 1 To UBound(PathFile)

    ' Find worksheet with name SheetX if one exists
    Found = False
    For InxWsht = 1 To Worksheets.Count
      If Left(Worksheets(InxWsht).Name, 5) = "Sheet" Then
        Worksheets(InxWsht).Activate
        Found = True
        Exit For
      End If
    Next

    If Not Found Then
      ' No free worksheet for this file
      Set WshtNew = Worksheets.Add(After:=Worksheets(Worksheets.Count))
    End If

    ' Active sheet (existing or new) is the sheet to which file is to be imported

    ' Extract file name from path name
    Pos = InStrRev(PathFile(InxFile), "\")
    If Pos = 0 Then
      ' No folder name.  Don't think this is possible.
      NameFileCrnt = PathFile(InxFile)
    Else
      ' Extract text after final \
      NameFileCrnt = Mid(PathFile(InxFile), Pos + 1)
    End If
    Pos = InStrRev(NameFileCrnt, ".")
    If Pos = 0 Then
      ' No extension
    Else
      ' Discard text after final .
      NameFileCrnt = Mid(NameFileCrnt, 1, Pos - 1)
    End If

    ' Use file name without path and extension as name of worksheet
    ActiveSheet.Name = NameFileCrnt

    With ActiveSheet.QueryTables _
      .Add(Connection:="TEXT;" & PathFile(InxFile), _
           Destination:=Range("A1"))        'Note I import to A1 not A3 as you do
      .Name = NameFileCrnt
      ' Replace the following with your values.  My test files
      ' had a different delimiter and were in UTF-7 format.
      ' Also I do not discard the initial rows of the file.
      ' to
      .FieldNames = True
      .RowNumbers = False
      .FillAdjacentFormulas = False
      .PreserveFormatting = True
      .RefreshOnFileOpen = False
      .RefreshStyle = xlInsertDeleteCells
      .SavePassword = False
      .SaveData = True
      .AdjustColumnWidth = True
      .RefreshPeriod = 0
      .TextFilePromptOnRefresh = False
      .TextFilePlatform = -535
      .TextFileStartRow = 1
      .TextFileParseType = xlDelimited
      .TextFileTextQualifier = xlTextQualifierDoubleQuote
      .TextFileConsecutiveDelimiter = False
      .TextFileTabDelimiter = False
      .TextFileSemicolonDelimiter = False
      .TextFileCommaDelimiter = False
      .TextFileSpaceDelimiter = False
      .TextFileOtherDelimiter = "|"
      .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
      .TextFileTrailingMinusNumbers = True
      .Refresh BackgroundQuery:=False
    End With

  Next

End Sub