获取与另一个字符串匹配的字符串的一部分

时间:2017-12-12 11:05:11

标签: excel vba excel-vba

我正在为Excel做VBA宏,我需要获取与特定字符串匹配的文件路径部分。

我的意思是,我有Variant名为FileInfo,其中包含我当时正在使用的工作簿的路径(在For中),例如,Variant可能看起来像:

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

我想创建一个只返回与"INC*"匹配的路径部分的函数,如果路径没有匹配,则返回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

使用部分解决方案进行编辑: 我使用以下代码来获取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

时会出现问题

3 个答案:

答案 0 :(得分:1)

只需在*中添加一个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

答案 1 :(得分:1)

您可以使用Split\从完整路径分离到PathArr数组元素,然后遍历PathArr元素并查找“< EM> 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

答案 2 :(得分:1)

获得结果的另一种方法

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