我試圖讓Excel 2007的宏打開一個文件夾,其中有一堆圖像。然後創建一個新的工作簿並將圖像嵌入其中。 「運行時錯誤‘434’:對象需要」如果我註釋掉線Sheet.Shapes.AddPicture FileName:=F, linktofile:=msoFalse, savewithdocument:=msoCTrue, Left:=cell.Left + 5, Top:=cell.Top + 5, Width:=560, Height:=310
如果我取消那行,我得到如何打開新工作簿並使用VBA添加圖像?
一切工作
我檢查Sheet.Shapes返回一個形狀的對象,它是但Shapes對象是空的。當我嘗試在宏外部打開的工作簿上使用Sheet.Shapes,AddPicture時,它會添加圖像。我也檢查過Sheet.Shapes.AddShape與在宏中打開的工作簿一起工作。
在這一點上,我對這個問題可能會有所損失。有沒有人有這種事情的經驗?我應該使用不同的方法嗎?提前感謝您的幫助或指導。
Sub Macro1()
Dim ImagePath, Flist
ImagePath = GetFolder()
If ImagePath = "" Then Exit Sub
Flist = FileList(ImagePath)
Name = "C:\target.xlsm"
Set Book = Workbooks.Add
Set Sheet = Book.Sheets(1)
For i = 1 To 5
cell = "C" + CStr(i)
F = ImagePath + "\" + Flist(i - 1)
Sheet.Shapes.AddPicture FileName:=F, linktofile:=msoFalse, _
savewithdocument:=msoCTrue, Left:=cell.Left + 5, Top:=cell.Top + 5, Width:=560, Height:=310
Next
Book.SaveAs FileName:=Name, FileFormat:=52
Book.Close
End Sub
Function FileList(ByVal fldr As String) As Variant
'Lists all the files in the current directory
'Found at http://www.ozgrid.com/forum/showthread.php?t=71409
Dim sTemp As String, sHldr As String
If Right$(fldr, 1) <> "\" Then fldr = fldr & "\"
sTemp = Dir(fldr & "*.png")
If sTemp = "" Then
FileList = False
Exit Function
End If
Do
sHldr = Dir
If sHldr = "" Then Exit Do
sTemp = sTemp & "|" & sHldr
Loop
FileList = Split(sTemp, "|")
End Function
Function GetFolder() As String
Folder:
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Title = "New Screenshot Folder"
.Show
num = .SelectedItems.Count
If .SelectedItems.Count = 0 Then
GetFolder = ""
Else: GetFolder = .SelectedItems(1)
End If
End With
End Function
您正在使用名爲** Name **,** cell **和其他保留名稱的變量,並且這肯定會導致錯誤。我建議總是用一個變量標識符來引導你的變量名,比如** i **,如果它是一個整數,** s **,如果它是一個字符串等等,這樣你就可以確保它們沒有使用保留的名字。 – cyberponk