提示使用obj.FSO.OpenTextFile打开txt文件

时间:2015-07-17 12:47:23

标签: excel excel-vba vba

编辑: 所以这是我当前的代码,在这个页面的帮助下 - 如何启用它,以便我可以在使用文件对话框功能打开后引入文本文件?

    Private Sub CommandButton1_Click()

Dim lngCount As Long

With Application.FileDialog(msoFileDialogOpen)
    .Filters.Add "Documents", "*.txt", 1
    .AllowMultiSelect = True
    .Show

End With

Const ForReading = 1

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("C:\test\copy.txt", ForReading) 'this is now defunct??

For i = 1 To 5
    objTextFile.ReadLine
Next

strLine = objTextFile.ReadLine
Range("A1").Value = strLine

objTextFile.Close
End Sub

1 个答案:

答案 0 :(得分:0)

从下一页(你几乎是正确的!)...... https://msdn.microsoft.com/en-us/library/office/ff836226.aspx

您可以使用此代码要求用户通过OpenFileDialog ...

打开文件
Sub UseFileDialogOpen() 

Dim lngCount As Long 

' Open the file dialog 
With Application.FileDialog(msoFileDialogOpen) 
    .AllowMultiSelect = True 
    .Show 

    ' Display paths of each file selected 
    For lngCount = 1 To .SelectedItems.Count 
        MsgBox .SelectedItems(lngCount) 
    Next lngCount 

End With 

End Sub