[英]How to get the browse file path in text box using VBA?
How to get the browse file name into text box ? 如何获取浏览文件名到文本框中? if get the file path, how to split the file name?
如果获取文件路径,如何分割文件名?
I tried application.GetOpenFilename("Text Files(*.txt),*.txt")
我尝试了
application.GetOpenFilename("Text Files(*.txt),*.txt")
Please advise to display into the text box and how to split the exact file name only to read the text file? 请建议在文本框中显示,以及如何仅读取文件来分割确切的文件名?
Don't waste your time reinventing the wheel: the FileSystemObject will do this for you. 不要浪费时间重新发明轮子: FileSystemObject将为您完成此任务。
Dim FSO As Object: Set FSO = CreateObject("Scripting.FileSystemObject")
Sheet1.TextBox1.Text = FSO.GetFilename("C:\mydir\myfile.dat")
The textbox now contains the text myfile.dat
. 现在,文本框包含文本
myfile.dat
。
The Dir function will give you the file name as long as it's a file that exists - and yours will be if you use GetOpenFilename. 只要存在文件,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
Here is a VBA routine to return the file name stripped of its path. 这是一个VBA例程,用于返回去除其路径的文件名。 Its easily modified to return the path instead, or both.
它很容易修改以返回路径,或者两者兼而有之。
'====================================================================================
' 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 click Button1单击
OpenFileDialog1.ShowDialog()
Me.TextBox1.Text = OpenFileDialog1.FileName
End Sub
Textbox1 change 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.