【问题标题】:VBA Excel: Specify Path To Import Text File Via Text Box on UserformVBA Excel:指定通过用户窗体上的文本框导入文本文件的路径
【发布时间】:2018-04-20 15:07:35
【问题描述】:

好的,我知道这是一种非常愚蠢的方法,但我有一个用户表单,允许用户输入 3 件事:文本文件所在的路径、文本文件的名称以及从文本文件中导入数据。我要做的是按照用户输入的路径,通过用户输入的名称获取文本文件,并将文本文件包含的任何内容放入用户输入的范围内。

我知道使用 Application.GetOpenFilename 可以很容易地简化它,但是你必须做你必须做的事情。我需要做的是能够指定路径、指定文本文件以及将文本文件中的所有文本加载到带有逗号分隔符的范围中的位置。目前,该程序要么在“.Refresh BackgroundQuery:=False”行中断,要么根本不做任何事情,我不知道如何前进。我的代码如下-为混乱道歉。如果您能提供帮助,请告诉我!

Private Sub OKButton_Click()

Dim filePath As String, destin As String, fileName As Variant

destin = DestinationTextBox.Value
fileName = TextFileNameTextBox.Value

filePath = Dir(FileLocationTextBox.Value)

'filePath = Application.GetOpenFilename("Text Files (*.txt), *.txt")
'oh, if only

    With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & _
    filePath, Destination:=Range(destin))
        .Name = fileName & ".txt"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierNone
        .TextFileConsecutiveDelimiter = True
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileOtherDelimiter = "" & Chr(10) & ""
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, _
           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
           1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
End With
End Sub

【问题讨论】:

  • 你的帖子我看了两遍,不知道是什么问题。可以edit转转吗?
  • 我已经编辑了,如果您需要更多说明,请告诉我!

标签: vba excel


【解决方案1】:

但我有一个用户表单,它允许用户输入 3 件事:文本文件所在的路径、文本文件的名称以及从文本文件导入数据的位置。

我想不出任何好的理由来分开路径和文件名,尤其是这样做会带来很多用户错误的机会,这意味着你必须添加很多错误处理逻辑来处理使用粗手指或错误输入的文件名或路径,在路径末尾添加或确保一致地使用路径分隔符(或不使用)以进行后续连接等。

这样的事情应该会让你走上正轨。使用TextBox 事件之一调用Application.FileDialog(msoFileDialogFilePicker),将所选项目的值(作为完整路径)返回给TextBox

Private Sub TextBox1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
' this event fires when user clicks in the textbox
' you may need to use other events also, but this is to illustrate
' call the procedure that actually does the work:
TextBox1.Value = getFileToOpen
End Sub
Private Function getFileToOpen()
' this function opens the FileDialog and returns the name of the selected file
Dim fileName As String
Dim fdlg As FileDialog
Dim f As FileDialogFilter
Set fdlg = Application.FileDialog(msoFileDialogFilePicker)
fdlg.Filters.Clear
Set f = fdlg.Filters.Add("Text Files", "*.txt", 1)
fdlg.FilterIndex = 1
If fdlg.Show Then
    fileName = fdlg.SelectedItems(1)
End If
getFileToOpen = fileName

End Function

如果您绝对必须保持两个TextBox 方法,则解析来自getFileToOpen 函数的结果值并根据需要分配给多个文本框。

另外,您的DestinationTextBox.Value 应该是RefEdit 控件,而不是TextBoxRefEdit 控件专门设计用于允许用户选择一系列单元格。

假设您的 QueryTable 出现 1004 错误,一个可能的罪魁祸首是您提供了文件的 路径,但没有提供文件的 名称。当你这样做时:

filePath = Dir(FileLocationTextBox.Value)

filePath 现在代表不是一个路径,而是一个文件Name!所以标识符filePath 令人困惑,因为这不是它包含的内容。

With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & _
    filePath

除非此文件 name 存在于活动工作簿的目录中(不太可能,但可能),否则 1004 错误是此代码唯一可能的结果,因为您在 @ 987654336@ 变量在活动目录中不存在。

(从技术上讲,这可以仅解析为工作目录中的文件,但很可能不存在这样的文件名

相反,在我上面提供的解决方案的基础上(使用FileDialog 确保您有一个有效的文件路径/文件名可供使用,而不依赖于笨拙的用户输入),请执行以下操作:

Dim fullFileName as String
fullFileName = TextFileNameTextBox.Value
' Make sure there's a value here
If fullFileName = vbNullString Then Exit Sub
' double-check that it's a valid path:
If Len(Dir(fullFileName)) = 0 Then Exit Sub

With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & _
    fullFileName & , ...

【讨论】:

  • 这非常有帮助,我很快就发现了我的问题:可悲的是,我必须保持两个文本框的格式(尽管存在大量人为错误的可能性)但是你建议的工作文件路径作为名称让我走上了完美的道路。赞
猜你喜欢
  • 2014-04-16
  • 1970-01-01
  • 2022-07-02
  • 2019-05-09
  • 1970-01-01
  • 1970-01-01
  • 2021-12-05
  • 2020-03-02
  • 1970-01-01
相关资源
最近更新 更多