如何使用VBA在文本框中获取浏览文件路径?

时间:2012-10-26 04:07:17

标签: excel vba excel-vba

如何将浏览文件名放入文本框?如果获取文件路径,如何拆分文件名?

我尝试了application.GetOpenFilename("Text Files(*.txt),*.txt")

请建议显示在文本框中以及如何拆分确切的文件名只读取文本文件?

5 个答案:

答案 0 :(得分:3)

不要浪费你的时间重新发明轮子:FileSystemObject会为你做这件事。

Dim FSO As Object: Set FSO = CreateObject("Scripting.FileSystemObject")
Sheet1.TextBox1.Text = FSO.GetFilename("C:\mydir\myfile.dat")

文本框现在包含文字myfile.dat

答案 1 :(得分:3)

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

答案 2 :(得分:1)

这是一个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

答案 3 :(得分:0)

最简单的方法是简单地阅读最终的"\";

tbx.text = mid$(someFileName, 1 + InStrRev(someFileName, "\"), Len(someFileName))

答案 4 :(得分:0)

按钮1单击

    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