我不确定这是否可行,但我想让用户输入要导入到 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
任何帮助将不胜感激!如果不可能,有没有类似的事情是可能的?