Excel VBA替换图像,创建PDF,移动到文件夹中的下一个图像并重复

时间:2016-04-18 13:17:30

标签: excel vba excel-vba

我有一个Excel工作表,我用作可打印的单页PDF报告,其中包含带有一些文本的图像。在一侧的列中,我有一个特定文件夹中所有图像的列表,我想使用VBA循环遍历列表,替换工作表中的图像,并创建一个PDF存储在同一文件夹中。我目前手动执行此操作,这很痛苦,并希望使用VBA自动执行此操作。

非常感谢任何帮助。

提前致谢。

我通过更改要替换的图像的完整路径来手动使用的代码如下>

Sub AddPicturesFULL()
 Dim myPic As Picture
 Dim wkSheet As Worksheet
 Dim myRng As Range
 Dim myCell As Range
 Dim rowCount As Long
 Dim rowCount2 As Long
 Dim Pic As Object

     Set wkSheet = Sheets("REPORT(FULL)") ' -- Change to your sheet

   For Each Pic In wkSheet.Pictures
   Pic.Delete
   Next Pic

    '-- The usual way of finding used row count for specific column
    rowCount2 = wkSheet.Cells(wkSheet.Rows.Count, "N").End(xlUp).Row

    If rowCount2 <> 0 Then
        Set myRng = wkSheet.Range("N2", wkSheet.Cells(wkSheet.Rows.Count, "N").End(xlUp))

        For Each myCell In myRng.Cells
               If Trim(myCell.Value) = "" Then
                    'MsgBox "No file path"
               ElseIf Dir(CStr(myCell.Value)) = "" Then
                    MsgBox myCell.Value & " Doesn't exist!"
               Else
                    'myCell.Offset(0, 1).Parent.Pictures.Insert (myCell.Value)
                    Set myPic = myCell.Parent.Pictures.Insert(myCell.Value)

                    With myCell.Offset(0, -13)  '1 columns to the right of C ( is D)
                        '-- resize image here to fit into the size of your cell
                        myPic.Top = .Top
                        myPic.Width = .Width
                        myPic.Height = 640
                        myPic.Left = .Left
                        myPic.Placement = xlMoveAndSize
                        myPic.SendToBack
                    End With
               End If
        Next myCell

    Else
        MsgBox "There is no file paths in your column"
    End If

End Sub

1 个答案:

答案 0 :(得分:1)

在工作表上创建ActiveX图像,而不是使用图纸

然后你可以使用

Dim i As Integer

For i = 1 To 20 Step 1

    imgTest.Picture = LoadPicture(Sheets("Sheet1").Cells(i, COLUMN).Value)

    Sheets("Sheets1").ExportAsFixedFormat Type:=xlTypePDF, Filename:="C:\test" & i & ".pdf", Quality:=xlQualityStandard
Next i

使用imagepaths遍历列并为每个列设置图像。然后只需将其导出为PDF格式。

当然,您必须根据需要调整i值和COLUMN。