使用用户输入文件名的VBA Excel导入.text

时间:2013-07-12 13:18:42

标签: excel vba excel-vba

我不确定这是否可行,但我想让用户输入要导入到文本文件的文件名(不是整个C:\ thing,而只是名称)的文件名Excel电子表格。我已经有了将文本文件(空格分隔)输入到电子表格的代码,但我真的不想每次要导入另一个文本文件时都返回并更改代码。这可能吗?该文件目前称为data.txt,但很可能采用Data_MM_DD_YY

的形式

我目前的代码如下:

Option Explicit


Public Sub ImportTextFile(FName As String, Sep As String)

Dim RowNdx As Long
Dim ColNdx As Integer
Dim TempVal As Variant
Dim WholeLine As String
Dim Pos As Integer
Dim NextPos As Integer
Dim SaveColNdx As Integer

Application.ScreenUpdating = False


SaveColNdx = ActiveCell.Column
RowNdx = ActiveCell.Row

Open FName For Input Access Read As #1

Name = InputBox("Enter the name of the text file")


While Not EOF(1)
    Line Input #1, WholeLine
    If Right(WholeLine, 1) <> Sep Then
        WholeLine = WholeLine & Sep
    End If
    ColNdx = SaveColNdx
    Pos = 1
    NextPos = InStr(Pos, WholeLine, Sep)
    While NextPos >= 1
        TempVal = Mid(WholeLine, Pos, NextPos - Pos)
        Cells(RowNdx, ColNdx).Value = TempVal
        Pos = NextPos + 1
        ColNdx = ColNdx + 1
        NextPos = InStr(Pos, WholeLine, Sep)
    Wend
    RowNdx = RowNdx + 1
Wend

EndMacro:
On Error GoTo 0
Application.ScreenUpdating = True
Close #1
End Sub

Sub DoTheImport()
ImportTextFile FName:="C:\Users\A0K045\Documents\Name).txt", Sep:=" "
End Sub

任何帮助将不胜感激!如果不可能,有什么类似的可能吗?

2 个答案:

答案 0 :(得分:0)

您只想在VBA之外更改文件名吗?当然,这没问题。

您可以创建一个带有文本框文本框的表单,然后将该目录附加到字符串中。

或者您可以让用户将文件名输入电子表格单元格并从中获取名称。

这是如何处理工作表中的输入:

Sub DoTheImport(ByVal strFilename As String)
    strFilename = "C:\Users\A0K045\Documents\" & strFilename
    ImportTextFile FName:=strFilename, Sep:=" "
End Sub
Sub getFilenameFromSheetAndGo()
    Dim strFilename As String
    strFilename = ActiveWorkbook.Worksheets("InputFilename").Cells(1, 1).Value 'Cell A1
    Call DoTheImport(strFilename)
End Sub

答案 1 :(得分:0)

询问名称并添加目录;

Name = InputBox("Enter the name of the text file")
If (Name = "") Then Exit Sub

open "c:\thedir\" & name for input as #1
...

或者您可以使用文件选择对话框;

Dim result As Variant
ChDir "c:\thedir\"
result = Application.GetOpenFilename("Text Files (*.txt),*.txt")
If (result = False) Then Exit Sub

open result for input as #1
...