在 Excel VBA 中打开 txt 文件
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.
你好我想打开一个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.