如何将浏览文件名放入文本框中?如果获取文件路径,如何拆分文件名?
我试过了application.GetOpenFilename("Text Files(*.txt),*.txt")
请建议显示到文本框中以及如何将确切的文件名拆分为仅读取文本文件?
不要浪费时间重新发明轮子: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 例程,用于返回去除其路径的文件名。它很容易修改为返回路径,或两者兼而有之。
'====================================================================================
' 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
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
最简单的方法是简单地从 final 中读取"\"
;
tbx.text = mid$(someFileName, 1 + InStrRev(someFileName, "\"), Len(someFileName))