vb 如何通过一个文件的全路径获得该文件所在文件夹

RT. 如现在已知"d:\123\123\asd\123.txt", 如何获取"d:\123\123\asd"

解决这个问题有两种方法。

第一种:知道了文件的全路径,那么路径中当然也包含文件所在的文件夹信息,只要从中提取即可。例如,已知文件全路径为“C:\Windows\System32\abc.dll”并赋予变量strPt,可用过下面语句获取文件夹。

left(strPt,instrrev(strPt,"\"))

instrrev函数的作用是从右侧开始查找指定字符串,并返回数值,此处返回值为20.left函数的作用是从左往右取N个字符,此例中取20个,最后结果为:C:\Windows\System32\。

第二种方法:使用FileSystemObject对象。代码如下:

dim fso as object, strFolder as object
set fso = createobject("scripting.filesystemobject")
set strFolder = fso.getfolder("C:\Windows\System32\abc.dll")
msgbox strFolder.path

文件系统对象FSO的英文全称是File System Object ,这种对象模型提出了有别于传统的文件操作语句处理文件和文件夹的方法。通过采用object.method这种在面向对象编程中广泛使用的语法,将一系列操作文件和文件夹的动作通过调用对象本身的属性直接实现。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-02-18
'编写函数,获取
Private Function GetLuJIn(ByVal a As String) As String
    Dim i As Long
    For i = Len(a) To 1 Step -1
        If mid(a,i,1) = "\" Then '获取最后一个"\"位置
            GetLuJin = Left(a,i-1) '函数返回最后一个"\"前面的东西
            Exit Function '获取之后,函数没什么事了,退出
        End if
    Next i
End Function

本回答被提问者采纳
第2个回答  2014-02-18
dim s as string
dim i
s="d:\123\123\asd\123.txt"

i=InStrRev(s,"\") ''最右侧 \ 字符位置
s =Left$(s, i-1) ''s即是路径(文件夹)d:\123\123\asd

debug.print s ''显示 d:\123\123\asd
第3个回答  2014-02-18
Private Sub Command1_Click()
   Dim i&, s$
   s = "d:\123\123\asd\123.txt"
   i = InStrRev(s, "\")
   If (i = 3) Then
      s = Left$(s, i)
   Else
      s = Left$(s, i - 1)
   End If
   MsgBox "路径为:" & s, 32
End Sub

相似回答