如何使用VBA获取文本框中的浏览文件path?
如何将浏览文件的名称放入文本框? 如果得到文件path,如何分割文件名?
我试过application.GetOpenFilename("Text Files(*.txt),*.txt")
请build议显示在文本框中,以及如何分割确切的文件名只读取文本文件?
不要浪费你的时间重新发明轮子: FileSystemObject将为你做这个。
Dim FSO As Object: Set FSO = CreateObject("Scripting.FileSystemObject") Sheet1.TextBox1.Text = FSO.GetFilename("C:\mydir\myfile.dat")
该文本框现在包含文本myfile.dat
。
只要它是一个存在的文件,Dir函数就会给你文件名,如果你使用GetOpenFilename,你的文件名就会变成你的文件名。
Sub GetFileName() Dim sFullName As String Dim sFileName As String sFullName = Application.GetOpenFilename("*.txt,*.txt") sFileName = Dir(sFullName) Debug.Print sFullName, sFileName End Sub
这是一个VBA例程,用于返回文件名称的path。 它很容易修改,以返回path,或两者兼而有之。
'==================================================================================== ' Returns the file name without a path via file open dialog box '==================================================================================== ' Prompts user to select a file. Which ever file is selected, the function returns ' the filename stripped of the path. Function GetAFileName() As String Dim someFileName As Variant Dim folderName As String Dim i As Integer Const STRING_NOT_FOUND As Integer = 0 'select a file using a dialog and get the full name with path included someFileName = Application.GetOpenFilename("Text Files (*.txt), *.txt") If someFileName <> False Then 'strip off the folder path folderName = vbNullString i = 1 While STRING_NOT_FOUND < i i = InStr(1, someFileName, "\", vbTextCompare) 'returns position of the first backslash "\" If i <> STRING_NOT_FOUND Then folderName = folderName & Left(someFileName, i) someFileName = Right(someFileName, Len(someFileName) - i) Else 'no backslash was found... we are done GetAFileName = someFileName End If Wend Else GetAFileName = vbNullString End If End Function
最简单的方法是简单地从最后的"\"
读取;
tbx.text = mid$(someFileName, 1 + InStrRev(someFileName, "\"), Len(someFileName))
button1单击
OpenFileDialog1.ShowDialog() Me.TextBox1.Text = OpenFileDialog1.FileName End Sub
Textbox1更改
Dim File As System.IO.FileInfo File = My.Computer.FileSystem.GetFileInfo(TextBox1.Text) Dim Path As String = File.DirectoryName TextBox2.Text = Path Dim fileName As String = File.Name TextBox3.Text = fileName End Sub