在excel vba中查找字符串中最后指定字符的位置

时间:2022-09-13 08:52:58

I want to know the position of the last "\" in the code below:

我想知道下面代码中最后一个“\”的位置:

Application.ActiveWorkbook.Path

2 个解决方案

#1


1  

You can use this code:

您可以使用此代码:

Path = Application.ActiveWorkbook.Path
CharacterSearch = "\"
x = InStr(Path, CharacterSearch)
Do Until InStr(x + 1, Path, CharacterSearch) = 0
x = InStr(x + 1, Path, CharacterSearch)
Loop
Debug.Print x

Where you loop to find all \ until InStr is 0, i.e.,until the last backlash is found.

循环找到所有\的地方,直到InStr为0,即直到找到最后一个反冲。

#2


2  

You use INSTR to find the location of one string within the other.

您使用INSTR查找一个字符串在另一个字符串中的位置。

For example:
C:\MyPC\SomeOtherPath - the backslash is in position 3 as shown in this code.
INSTR("C:\MyPC\SomeOtherPath", "\")

例如:C:\ MyPC \ SomeOtherPath - 反斜杠位于位置3,如此代码所示。 INSTR(“C:\ MyPC \ SomeOtherPath”,“\”)

This doesn't give you what you want though - you want the reverse of this. Luckily VBA gives that with INSTRREV:

这并没有给你你想要的东西 - 你想要反过来。幸运的是VBA给了INSTRREV:

INSTRREV("C:\MyPC\SomeOtherPath", "\")

This returns the position of the last backslash - in position 8.

这将返回最后一个反斜杠的位置 - 位置8。

#1


1  

You can use this code:

您可以使用此代码:

Path = Application.ActiveWorkbook.Path
CharacterSearch = "\"
x = InStr(Path, CharacterSearch)
Do Until InStr(x + 1, Path, CharacterSearch) = 0
x = InStr(x + 1, Path, CharacterSearch)
Loop
Debug.Print x

Where you loop to find all \ until InStr is 0, i.e.,until the last backlash is found.

循环找到所有\的地方,直到InStr为0,即直到找到最后一个反冲。

#2


2  

You use INSTR to find the location of one string within the other.

您使用INSTR查找一个字符串在另一个字符串中的位置。

For example:
C:\MyPC\SomeOtherPath - the backslash is in position 3 as shown in this code.
INSTR("C:\MyPC\SomeOtherPath", "\")

例如:C:\ MyPC \ SomeOtherPath - 反斜杠位于位置3,如此代码所示。 INSTR(“C:\ MyPC \ SomeOtherPath”,“\”)

This doesn't give you what you want though - you want the reverse of this. Luckily VBA gives that with INSTRREV:

这并没有给你你想要的东西 - 你想要反过来。幸运的是VBA给了INSTRREV:

INSTRREV("C:\MyPC\SomeOtherPath", "\")

This returns the position of the last backslash - in position 8.

这将返回最后一个反斜杠的位置 - 位置8。