2017-04-11 58 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 
相关问题