如何將瀏覽文件名稱導入文本框?如果獲取文件路徑,如何分割文件名?如何使用VBA獲取文本框中的瀏覽文件路徑?
我試圖application.GetOpenFilename("Text Files(*.txt),*.txt")
請指教,顯示在文本框中,如何只拆分的確切文件名來讀取文本文件?
如何將瀏覽文件名稱導入文本框?如果獲取文件路徑,如何分割文件名?如何使用VBA獲取文本框中的瀏覽文件路徑?
我試圖application.GetOpenFilename("Text Files(*.txt),*.txt")
請指教,顯示在文本框中,如何只拆分的確切文件名來讀取文本文件?
這裏是一個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
我期待這個答案......謝謝。 – user441978
不要浪費你的時間重新發明輪子:FileSystemObject會爲你做這個。
Dim FSO As Object: Set FSO = CreateObject("Scripting.FileSystemObject")
Sheet1.TextBox1.Text = FSO.GetFilename("C:\mydir\myfile.dat")
該文本框現在包含文本myfile.dat
。
最簡單的方法是簡單地從最終"\"
讀取;
tbx.text = mid$(someFileName, 1 + InStrRev(someFileName, "\"), Len(someFileName))
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
如何設置文件以選擇所有類型?我可以把(「所有文件,*。*」)? –
'sFullName = Application.GetOpenFilename(「*。*,*。*」)'將顯示所有文件類型 –
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
我可以給你答案,但如果你鍵入'GetOpenFilename'在VBA編輯器,並選中它,然後按法寶'F1'它會給你你需要的代碼;) –
關於你的第二個問題,你可以使用「\」作爲分隔符來分割路徑來提取文件名。看到這個鏈接http://stackoverflow.com/questions/13068090/how-to-get-current-directory-name-in-macros-programming/13068192#13068192 –