获取与另一个string匹配的string的一部分

我正在做Excel的VBAmacros,我需要得到与特定string匹配的文件path的一部分。

我的意思是,我有一个名为FileInfoVariant ,它包含我在那个时候(在For中)使用的Workbook的path,例如,Variant可能如下所示:

 C:\Users\myUser\Desktop\SVN-Folder\trunk\G\INC20825\Estimación Temporal_v01r00.xlsx 

我想做一个函数,只返回与"INC*"匹配的path部分,如果path没有匹配,则返回null。

所以这种情况下的函数可能会返回: INC20825

我试过这个,但没有工作

 'This function returns the INC folder where is contained Function INCFolder(FileInfo As Variant) Dim i As Integer If FileInfo Like "INC*" Then i = InStr(FileInfo, "INC") INCFolder = Mid(FileInfo, i, 8) Else INCFolder = Null End If End Function 

编辑与部分的解决scheme:我使它的工作获得INC*的8个字符与下面的代码:

 'This function returns the INC folder where is contained Function INCFolder(FileInfo As Variant) Dim i As Integer i = InStr(FileInfo, "INC") If i = 0 Then INCFolder = Null Else INCFolder = Mid(FileInfo, i, 8) End If End Function 

INC大于或小于8时会出现问题

您可以使用Split将您的\从您的完整path分隔到PathArr数组元素,然后循环遍历PathArr元素并查找INC

下面的代码将为您提供“ INC ”字符的灵活性。

 Option Explicit Sub test() Const FullName = "C:\Users\myUser\Desktop\SVN-Folder\trunk\G\INC20825\Estimación Temporal_v01r00.xlsx" Dim INCSection As String INCSection = INCFolder(FullName) End Sub 

 Function INCFolder(FileInfo As Variant) As String Dim i As Long Dim PathArr As Variant If FileInfo Like "*INC*" Then PathArr = Split(FileInfo, "\") ' split folders to array For i = 0 To UBound(PathArr) ' loop through array and look for "*INC*" If PathArr(i) Like "*INC*" Then INCFolder = PathArr(i) Exit Function End If Next i Else INCFolder = "Error!" End If End Function 

只需在Like添加一个*

 Option Explicit Public Const pathName = "C:\Folder\trunk\G\INC20825\Estimación Temporal_v01r00.xlsx" Function INCFolder(FileInfo As Variant) Dim i As Long If FileInfo Like "*INC*" Then i = InStr(FileInfo, "INC") INCFolder = Mid(FileInfo, i, 8) Else INCFolder = False End If End Function 

只是获得结果的替代方法

 Function INCFolder(FileInfo As Variant) If FileInfo Like "*INC*" Then INCFolder = Mid(WorksheetFunction.Substitute(Mid(FileInfo, InStr(FileInfo, "\INC"), Len(FileInfo)), "\", "|", 2), 2, WorksheetFunction.Search("|", WorksheetFunction.Substitute(Mid(FileInfo, InStr(FileInfo, "\INC"), Len(FileInfo)), "\", "|", 2)) - 2) Else INCFolder = Null End If End Function