下面的代码应该在同一用户窗体上名为 Image1 的图像控制框中显示预览图像,但事实并非如此,在 Image1.Picture = LoadPicture(Environ("TEMP") & "\PrintPreview.png") 处出现了阻塞,我检查了Temp目录,它把PrintPreview.png文件保存为PrintPreview.png.pdf,所以无法将其加载到图像控制框,有什么办法解决吗?
Private Sub CommandButton8_Click()
Application.EnableEvents = False
Me.Hide
' Create a temporary worksheet to hold the print area
Dim tempSheet As Worksheet
Set tempSheet = Sheets.Add
' Copy the desired range to the temporary sheet
Worksheets("InputSheet").Range("A1:I31").Copy tempSheet.Range("A1")
' Set print area for the temporary sheet
tempSheet.PageSetup.printArea = tempSheet.UsedRange.Address
' Create a chart to capture a screenshot of the print preview
Dim tempChart As ChartObject
Set tempChart = tempSheet.ChartObjects.Add(0, 0, tempSheet.UsedRange.Width, tempSheet.UsedRange.Height)
' Copy the temporary sheet to the chart
tempChart.Chart.Paste
' Export the chart as an image
tempChart.Chart.Export Environ("TEMP") & "\PrintPreview.png", "PNG"
' Delete the temporary sheet and chart
Application.DisplayAlerts = False
tempSheet.Delete
Application.DisplayAlerts = True
' Load the captured image into the Image control
Image1.Picture = LoadPicture(Environ("TEMP") & "\PrintPreview.png")
' Show the UserForm again
Me.Show
Application.EnableEvents = True
End Sub
当我单击按钮时,我期望 PrintPreview.png 图像出现在同一用户窗体上的图像控制框“Image1”中
正如 @BlackCat 所提到的,VBA 本身并不处理 PNG 文件,因此您需要添加更多代码来完成此操作。可以使用以下函数,对上面的代码进行最小的更改:
Function LoadImage(ByVal Filename As String) As StdPicture
With CreateObject("WIA.ImageFile")
.LoadFile Filename
Set LoadImage = .FileData.Picture
End With
End Function
因此,您只需将相关代码行更改为:
Image1.Picture = LoadImage(Environ("TEMP") & "\PrintPreview.png")
希望有帮助。