如何在Excel工作表中提取完整路径的文件名

时间:2018-10-26 07:12:31

标签: excel vba

我需要提取B列的文件名,例如从pm5a1tktzlrzzgno2r5l.png中提取v1448360146/pm5a1tktzlrzzgno2r5l.png并将结果与​​A列中的值进行比较。

image shown here

3 个答案:

答案 0 :(得分:1)

分割文件名和扩展名,然后在A列中找到匹配项。

sub huh()

    dim m as variant, str as string, i as long

    with worksheets("sheet1")
        for i = 1 to .cells(.rows.count, "B").ens(xlup).row
            str = split(.cells(i, "B").value2, chr(47))(ubound(split(.cells(i, "B").value2, chr(47))))
            m = application.match(str, .range("A:A"), 0)
            if not iserror(m) then
                'm is the row number in column A of the matching filename
                debug.print .cells(m, "A").value
                'do something with it
            end if
        next i
    end with

end sub

答案 1 :(得分:1)

更改工作表名称,设置正确的范围,然后尝试:

Sub Test()

Dim Lr As Long
Dim Position As Long
Dim str As String
Dim i As Long

With Sheets("Sheet1") '<= Change SheetName if needed
    Lr = .Cells(.Rows.Count, "A").End(xlUp).Row

    For i = 1 To Lr
        Position = InStrRev(.Cells(i, "B").Value, "/") + 1
        str = Mid(.Cells(i, "B").Value, Position, ((Len(.Cells(i, "B").Value)) - (Position - 1)))
        If str = .Cells(i, "A").Value Then
            MsgBox "Same!"
        End If
    Next i
End With

End Sub

答案 2 :(得分:1)

打开Excel文件,按Alt + F10(或从面板启动VBEditor),然后在其中创建一个新模块(“插入”>“新模块”)。将以下代码放入新模块中:

Sub extractFileNames()
Dim rng As Range

'Set your own input range with A and B columns and worksheet name here.
Set rng = ThisWorkbook.Worksheets("Your_worksheet_name").Range("A1:B1000")

Dim arr As Variant
arr = rng.Value2  

For i = 1 To UBound(arr)
    Dim tmp() As String
    tmp = Split(arr(i, 2), "/")
    arr(i, 1) = tmp(UBound(tmp))      
Next i
rng.Value2 = arr 
End Sub

您可以使用(see the link, if you don't know how)所支持的任何方式来运行此宏。

此外,如果您不想在文件中使用宏,则可以尝试使用诸如 = RIGHT($ B2,LEN($ B2)-FIND(“ /”,$ B2))之类的函数。 ,但是如果路径太多或它们的分度数不同,那将无济于事。