2017-01-22 137 views
0

如果單元格包含位於指定目錄中的圖像名稱(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 

它會停在不具有位於它正在尋找在目錄中的圖片名稱的行中的問題。

如果在相應的目錄中沒有該圖像並將其放到所有行的末尾,是否有辦法跳過該行?

回答

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 
+0

不錯!謝謝,我正在使用Mac,但我會放棄它。 – CFlynn

相關問題