如果目录中不存在文件,则跳过行

时间:2017-01-22 23:48:05

标签: excel vba excel-vba

我一直在研究一个宏,如果单元格包含指定目录中的图像名称(image1.png),它会将图像添加到单元格中。因此,如果它在目录中找到“image1.png”,它会将图像添加到单元格并移动到下一行。这是迄今为止的代码:

Option Explicit

Sub insertPicss()
Dim ws As Worksheet, cell As Range
Set ws = ThisWorkbook.Sheets("Sheet1")

Dim fPath, fDir As String

fDir = "Macintosh HD:Users:Connor:Desktop:siteimages:"
For Each cell In ws.[A1:A12]
    fPath = fDir & cell.Value
    With ws.Pictures.Insert(fPath)
        With .ShapeRange
            .Width = 48
            .Height = 48
        End With
        .PrintObject = True
        .Top = cell.Top
        .Left = cell.Left
    End With
Next

End Sub

它在没有图像名称的行中停止的问题位于它正在查看的目录中。

如果在相应目录中没有该图像并将其放到所有行的末尾,是否可以跳过该行。

1 个答案:

答案 0 :(得分:0)

在Windows中,使用Dir检查文件/文件夹是否存在。

以下适用于Windows,但不确定Mac。

Option Explicit

Sub insertPicss()
    Dim ws As Worksheet, cell As Range
    Set ws = ThisWorkbook.Sheets("Sheet1")

    Dim fPath, fDir As String

    fDir = "Macintosh HD:Users:Connor:Desktop:siteimages:"
    For Each cell In ws.[A1:A12]
        fPath = fDir & cell.Value
        If Dir(fPath) = cell.Value Then ' If Not Dir(fPath) = "" Then
            With ws.Pictures.Insert(fPath)
                With .ShapeRange
                    .Width = 48
                    .Height = 48
                End With
                .PrintObject = True
                .Top = cell.Top
                .Left = cell.Left
            End With
        End If
    Next

End Sub