简体   繁体   English

VSTR中的InSTR或查找功能

[英]InSTR or find function in VBA

I am stuck with an issue. 我陷入一个问题。 I've done my research and found out that I can use InSTR function to search for a specific character in a string. 我完成了研究,发现可以使用InSTR函数搜索字符串中的特定字符。

What I am trying to do is get a file name extracted from a file path. 我想做的是获取从文件路径中提取的文件名。

Currently I have 目前我有

  InStr(StrFrom(pName), "\")

The issue here is, it returns the first occurrence of slash, where as I want to get the last occurrence of the slash (so that I can use a 'right' function wrapped around the above code to capture the file name) 这里的问题是,它返回第一个出现的斜杠,因为我想获取最后一个出现的斜杠(以便我可以使用包裹在上面代码中的“正确”功能来捕获文件名)

Any help is appreciated on how to get the last slash in a string! 感谢您提供有关如何获取字符串中最后一个斜杠的任何帮助!

Thanks! 谢谢!

Instr looks from the start of the text string, InstrRev starts looking from the other end. Instr从文本字符串的InstrRev开始看, InstrRev从另一端开始看。

Public Function FileNameOnly(ByVal FileNameAndPath As String) As String

    FileNameOnly = Mid(FileNameAndPath, InStrRev(FileNameAndPath, "\") + 1, Len(FileNameAndPath))

End Function

Use InStrRev() to find the first occurrence of the slash from the right side of the string. 使用InStrRev()从字符串的右侧查找第一个出现的斜杠。

https://msdn.microsoft.com/en-us/library/t2ekk41a(v=vs.90).aspx https://msdn.microsoft.com/zh-CN/library/t2ekk41a(v=vs.90).aspx

Consider: 考虑:

Sub marine()
    Dim s As String, ary
    s = "C:\whatever\sub1\sub2\reallydeep\x.xlsm"
    ary = Split(s, "\")
    MsgBox ary(UBound(ary))
End Sub

在此处输入图片说明

Assuming StrFrom is some user defined function, the following will do what you want: 假设StrFrom是一些用户定义的函数,则下面的操作将满足您的要求:

Dim filename as String
Dim path as String

path = StrFrom(pName)
filename = Mid$(path, InstrRev(path, "\") + 1)

Note that its easier to use Mid$ than Right$, as InstrRev returns the character position from the left of the string. 注意,由于InstrRev从字符串的左边返回字符位置,因此它比Right $更易于使用Mid $。 Omitting the final parameter of Mid$, returns the rest of the string from that position. 省略Mid $的最后一个参数,从该位置返回字符串的其余部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM