简体   繁体   English

在Excel VBA中打开txt文件

[英]Open txt file in Excel VBA

Hi I want to open a txt file (need to pop open file dialog box and the same folder as the current template) 嗨,我想打开一个txt文件(需要弹出打开文件对话框以及与当前模板相同的文件夹)

Then this file need to read as xlsx rather than txt. 然后,此文件需要读取为xlsx而不是txt。

This is my current code setup: 这是我当前的代码设置:

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

Can someone identify my mistakes? 有人可以识别我的错误吗?

You can try the following code snippet (it works) and modify it pertinent to your development task: 您可以尝试以下代码片段(它可以工作)并根据您的开发任务对其进行修改:

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

Hope this may help. 希望这会有所帮助。 Kind regards, 亲切的问候,

Or you can use this: 或者您可以使用以下命令:

Dim fname
fname = Application.GetOpenFilename("Text Files (*.txt),*.txt", , , , True)
If IsArray(fname) Then Workbooks.OpenText fname(1)

To see the available arguments OpenText Method offers, see MSDN . 要查看OpenText方法提供的可用参数,请参见MSDN HTH. HTH。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM