[英]Open txt file in Excel VBA
嗨,我想打开一个txt文件(需要弹出打开文件对话框以及与当前模板相同的文件夹)
然后,此文件需要读取为xlsx而不是txt。
这是我当前的代码设置:
Private Sub CommandButton1_Click()
Dim intChoice As Integer
'Select the start folder
Application.FileDialog(msoFileDialogOpen _
).InitialFileName = "I:\Group -*******Chages here******"
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If intChoice <> 0 Then
***** CODE HERE********
End If
End Sub
有人可以识别我的错误吗?
您可以尝试以下代码片段(它可以工作)并根据您的开发任务对其进行修改:
Private Sub CommandButton1_Click()
Dim fDialog As Office.FileDialog
' set up the File Dialog var
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
'sample init file name
.InitialFileName = "C:\Text.txt"
' set the title of the Dialog box
.Title = "Please select the file to open"
' Clear the current and add some sample filters
.Filters.Clear
.Filters.Add "Text Files", "*.txt"
.Filters.Add "Excel Files", "*.xls"
.Filters.Add "All Files", "*.*"
'Show dialog box: if .Show method returns True then execute the code
If .Show = True Then
'Add code here
Else
MsgBox "File Open operation Canceled."
End If
End With
End Sub
希望这会有所帮助。 亲切的问候,
或者您可以使用以下命令:
Dim fname
fname = Application.GetOpenFilename("Text Files (*.txt),*.txt", , , , True)
If IsArray(fname) Then Workbooks.OpenText fname(1)
要查看OpenText方法提供的可用参数,请参见MSDN 。 HTH。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.