我不確定這是否可能,但我想讓用戶輸入文本文件的文件名(不是整個C:\東西,但是隻是名稱),這是要導入到Excel電子表格中。我已經得到了用於向電子表格輸入文本文件(空格分隔)的代碼,但是我真的很想在每次我想要導入另一個文本文件時都不要返回並更改代碼。這可能嗎?目前該文件稱爲data.txt中,但它很有可能會在Data_MM_DD_YY用戶輸入文件名VBA Excel導入.txt
我當前的代碼如下形式:
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
任何幫助將不勝感激!如果這是不可能的,是否有類似的可能嗎?
有什麼特定的我需要鍵入單元格A1的文件名?我試過data和data.txt和「data」和「data.txt」,並且我不斷收到下標超出範圍的錯誤。難道我做錯了什麼? 謝謝! – Rawr