尝试将所选文本文件导入到单元格A1

时间:2017-11-24 12:30:31

标签: excel vba text import filedialog

我正在尝试创建一个宏,我提示用户选择一个文本文件,然后将所选文本文件的内容导入到单元格中。我设法得到了filedialog并让用户选择文件,但后来我不知道如何继续导入文件。有人可以帮忙吗?

这是我到目前为止的(工作)代码:

 Sub ImportFile()
Dim dFile As FileDialog, result As Integer, it As Variant
Set dFile = Application.FileDialog(msoFileDialogOpen)

dFile.InitialFileName = "G:\"


If dFile.Show = -1 Then
  Debug.Print dFile.SelectedItems(1)
End If


End Sub

提前谢谢!

1 个答案:

答案 0 :(得分:0)

您正在使用下面的代码,它将导入您的整个.txt。文件,到二维数组。之后,您需要遍历行维度,并将每行的列复制到工作表中,从第1行开始。

<强>代码

Option Explicit

Sub ImportFile()

Dim fNum As Integer
Dim WholeFile As String
Dim FileName As String
Dim Arr As Variant, ArrRow As Variant
Dim i As Long, Col As Long

Dim dFile As FileDialog, result As Integer, it As Variant

Set dFile = Application.FileDialog(msoFileDialogOpen)
dFile.InitialFileName = "G:\"

If dFile.Show = -1 Then
    FileName = dFile.SelectedItems(1)
End If

fNum = FreeFile
Open FileName For Input As fNum
WholeFile = Input$(LOF(fNum), #fNum)
Close fNum

Arr = Split(WholeFile, vbCrLf) ' Break the file into lines (array) change vbCrLf to your rows delimeter

' loop through Array rows
For i = 0 To UBound(Arr) - 1
    ArrRow = Split(Arr(i), ",")   '  break the row to columns , change "," to your delimeter
    Range("A" & i + 1).Resize(1, UBound(ArrRow)).Value = ArrRow
Next i

End Sub