簡體   English   中英

在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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM