Excel宏:将单元格值与外部文件名/文件夹内容进行比较

时间:2019-01-14 20:39:33

标签: excel vba

我需要完成此代码,您能帮我吗? 我必须在Excel宏中使用它。该宏必须检查每个单元格中写入的内容(在其中包含歌曲名称)是否以文件形式存在于特定的文件夹中。例如,如果某个单元格中没有其他内容,脚本将必须检查该文件夹中是否有该名称的文件。这是一个应该节省时间的脚本,对于出现的错误我深表歉意,但这是我第一次把手放在这种语言上(不是我的作品,为了公平起见,我说这句话)。

出现的错误如下:

  

编译错误:

     

语法错误

问题出在“ If Dir(songname)”“那么

Sub Test_if_File_exists_in_dir()

Dim RangeOfCells As Range
Dim Cell As Range
Dim songname As String

Dim TotalRow As Long

TotalRow = Range("A" & Rows.Count).End(xlUp).Row

Set RangeOfCells = Range("A2:A" & TotalRow)

For Each Cell In RangeOfCells
    songname = "C:\Alessio\Songs\" & Cell & ".*"

        If Dir(songname)  "" Then 
            Cell.Font.Color = vbRed
        Else
            Cell.Font.Color = vbBlack
        End If

Next Cell
MsgBox "Done, verify data first time"

End Sub

谢谢

Alessio

1 个答案:

答案 0 :(得分:0)

尝试一下:

Sub Test_if_File_exists_in_dir()

    Dim RangeOfCells As Range
    Dim Cell As Range
    Dim songname As String

    Dim TotalRow As Long

    TotalRow = Range("A" & Rows.Count).End(xlUp).Row

    Set RangeOfCells = Range("A2:A" & TotalRow)

    For Each Cell In RangeOfCells
        'edit: include artist
        songname = "C:\Alessio\Songs\" & _
                    Cell.Offset(0, 1) & " - " & Cell & ".*"
        Debug.print "Checking: " & songname
        Cell.Font.Color = IIf(Len( Dir(songname) ) = 0, vbRed, vbBlack)

    Next Cell
    MsgBox "Done, verify data first time"

End Sub