Dum*_*iel 4 excel vba function
我一直试图从文件结构中找到扩展名,为此我很难使用InstrRev(文件名,".")而不是返回4,它返回30,与Instr一样......
有人知道一个奇怪的错误会导致excel给2个相反的函数提供相同的结果吗?
亲切的问候,丹尼尔
Instr和之间的区别InstrRev是它寻找某个子串的方向.Instr正在InstrRev从头到尾看,同时从字符串的末尾到开头.该结果字符位置总是从字符串的开头计数的(从左至右).
我想在你的例子中,你"."的路径中只有一个,这就是结果相同的原因.
让我们考虑一个你正在寻找"干净"文件名的情况,所以你正在寻找最后一个\,然后你会发现这个InStrRev函数非常有用(例如见下面的代码).
对于你的情况:如果你想找到扩展名,让我们说结果是31,那么使用Mid函数:
ExtensionStr = Mid(FullName, dotRes + 1, Len(FullName) - dotRes) ' < --- returns "xlsm"
Run Code Online (Sandbox Code Playgroud)
(dotRes= 31,ExtensionStr是表示干净扩展名的字符串)
代码示例
Sub Instr_InstrRev()
Dim instrRes As Variant
Dim instrRevRes As Variant
Dim dotRes As Variant
Dim ExtensionStr As String
Dim FullName As String
FullName = "C:\Users\Radoshits\Desktop\SO2.xlsm"
instrRes = InStr(FullName, "\") ' <-- returns 3
instrRevRes = InStrRev(FullName, "\") ' <-- returns 27
' to answer your post how to find the "clean" extension name
dotRes = InStr(FullName, ".") ' <-- returns 31
ExtensionStr = Mid(FullName, dotRes + 1, Len(FullName) - dotRes) ' < --- returns "xlsm"
End Sub
Run Code Online (Sandbox Code Playgroud)