问题描述
我想在父文件路径之后获取带有扩展名的文件名。例如:从C:\ Desktop \ Pictures \ picture.jpg检索picture.jpg。 *注意:我不知道文件或图片的名称是什么。用户将自己添加这些名称,我想检索该名称以将其显示在表单上。
这是我到目前为止所拥有的...
Private Sub InsertimageButton_Click()
Dim strImageID As String
Dim strFolder As String
Dim fso As Object
Dim strFormat As String
Const strParent = "C:\Desktop\Pictures\"
strImageID = Me.ImageID.Value
strFormat = Format(strImageID,"20-0000")
'Parent Path
strFolder = strParent & strFormat
'Create FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
'Check Whether Folder Exists
If fso.FolderExists(strFolder) = False Then
'If not,create it
fso.CreateFolder strFolder
End If
'Open It
Shell "C:\Windows\explorer.exe """ & strFolder & "",vbnormalFocus
*打开文件夹后,用户应在此处插入新图片。 之后,我希望文本框显示完整的路径名,以便它也可以获取图片的名称。
'This is where I am stuck.
Me.[txtimageName].Value = strFolder & "\" & GetFilenameFromPath(strFolder)
我尝试从其他Stack Overflow问题中添加一个函数,但这没有帮助。
Public Function GetFilenameFromPath(ByVal strPath As String) As String
' Returns the rightmost characters of a string upto but not including the rightmost '\'
' e.g. 'c:\winnt\win.ini' returns 'win.ini'
Dim picturepath As String
If Right$(strPath,1) <> "\" And Len(strPath) > 0 Then
GetFilenameFromPath = GetFilenameFromPath(Left$(strPath,Len(strPath) - 1)) + Right$(strPath,1)
End If
End Function
当前代码给我C:\ Desktop \ Pictures \ 20-0012 \ 20-0012 我需要添加的图片名称,而不知道添加了什么。 预先感谢!
解决方法
请尝试下一个功能,
Function GetFileName(strFullName As String) As String
GetFileName = Split(strFullName,"\")(UBound(Split(strFullName,"\")))
End Function
如果讨论中的文件夹包含单个文件,则应该以这种方式测试上述功能:
dim fullFileName As String
fullFileName = Dir(strFolder & "\*.jpg")
MsgBox GetFileName(fullFileName)
,
Public Function GetFilenameFromPath(ByVal strPath As String) As String
GetFilenameFromPath = Mid(strPath,InStrRev(strPath,"\") + 1)
End Function