1

我不确定这是否可行,但我想让用户输入要导入到 Excel 电子表格中的文本文件的文件名(不是整个 C:\,而只是名称)。我已经有了将文本文件(空格分隔)输入到电子表格的代码,但我真的不想每次我想导入另一个文本文件时都返回并更改代码。这可能吗?该文件当前称为 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

任何帮助将不胜感激!如果不可能,有没有类似的事情是可能的?

4

2 回答 2

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
于 2013-07-12T13:28:08.790 回答
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
...
于 2013-07-12T13:29:40.280 回答