2017-04-11 60 views
0

有沒有什麼方法可以使用VBA我們可以運行一個窗口選擇一個文件,當我們點擊它時,名稱應該被複制而沒有擴展名(.txt),並且應該被複制到表單中「 TEXT「,單元格AZ2。在一個特定的單元格中獲取文件名

我從一些代碼開始,但它不工作。不知道如何進一步做。

Sub Main_Macro() 
Dim fName As String, LastRowim As Long 

fName = Application.GetOpenFilename("Text Files (*.txt), *.adt") 
If fName = "False" Then Exit Sub 

End Sub 

回答

0

嘗試使用GetBaseName()方法獲取沒有擴展名的文件的名稱。

+0

謝謝你,但其實我是很新的VBA編碼。如果你能告訴我如何在代碼中實現它,這將對我非常有幫助。 – Sanoj

+0

你可以簡單介紹一下代碼嗎?我需要文件名稱反映在表單「TEXT」的單元格AZ2中。 – Sanoj

0

怎麼是這樣的:

Sub foo() 
    Dim fd As FileDialog 
    Dim fName As String ' Includes full path 
    Dim fChosen As Integer 
    Dim fNameFile As String 'Only the name of the file 

    Set fd = Application.FileDialog(msoFileDialogFilePicker) 'open dialog box 
      fd.Title = "Please select file" 'dialog Title 
      fd.InitialFileName = "C:\Users\" 'Path to initiate Dialog box 
      'fd.InitialFileName = ThisWorkbook.Path & "\" 'alternate initial path 
      fChosen = fd.Show 
        fd.Filters.Clear 
        'fd.Filters.Add "CSV files", "*.csv" 'add filters to only show this type of file 
        fd.Filters.Add "Text files", "*.txt" 'in this case only txt files will be selectable 

     If fChosen <> -1 Then 
      MsgBox "You Cancelled, nothing done!", vbInformation 
     Else 
      fName = Right$(fd.SelectedItems(1), Len(fd.SelectedItems(1)) - InStrRev(fd.SelectedItems(1), "\")) 'get full path of file, then remove anything prior to \ to get filename 
      Position = InStr(fName, ".") 'get the position of the extension 
      If Position > 0 Then Extension = Right(fName, Len(fName) - Position + 1) 'get the actual extension of the file 
      fName = Replace(fName, Extension, "") 'remove that extenstion 
      Sheets("TEXT").Range("AZ2").Value = fName 'enter the file name to your chosen range 
     End If 
End Sub 
相關問題