尝试在 G8 列中嵌入文件,显示图标为 true。宽度等
Sub InsertObjectsFromFiles()
Dim ws As Worksheet
Dim lastRow As Long
Dim filePath As String
Dim i As Long
Dim obj As OLEObject
Dim fileExists As Boolean
' Set the worksheet you are working on
Set ws = ThisWorkbook.Sheets("Sheet1") ' Change Sheet1 to your sheet name
' Find the last row with data in column F
lastRow = ws.Cells(ws.Rows.Count, "F").End(xlUp).Row
' Loop through rows from row 8 to the last used row in column F
For i = 8 To lastRow
' Get the file path from column F
filePath = ws.Cells(i, "F").Value
' Check if the file path is not empty
If filePath <> "" Then
' Check if the file exists
fileExists = Dir(filePath) <> ""
If fileExists Then
On Error Resume Next
' Insert object from file, display as icon
Set obj = ws.OLEObjects.Add(ClassType:="Package", FileName:=filePath, _
Link:=False, DisplayAsIcon:=True, _
IconLabel:=Dir(filePath), Left:=ws.Cells(i, "G").Left, _
Top:=ws.Cells(i, "G").Top, Width:=100, Height:=100)
If Err.Number <> 0 Then
MsgBox "Error inserting file: " & filePath & vbCrLf & "Error: " & Err.Description, vbCritical
Err.Clear
End If
On Error GoTo 0
Else
MsgBox "File not found: " & filePath, vbExclamation
End If
End If
Next i
End Sub
出现错误
运行时错误“1004”:
无法获取 OLEObjects dass 的 Add 属性
这应该有效
Sub InsertObjectsFromFiles()
Dim ws As Worksheet
Dim lastRow As Long
Dim filePath As String
Dim i As Long
Dim obj As OLEObject
Dim fileExists As Boolean
' Set the worksheet you are working on
Set ws = ThisWorkbook.Sheets("Sheet1") ' Change Sheet1 to your sheet name
' Find the last row with data in column F
lastRow = ws.Cells(ws.Rows.Count, "F").End(xlUp).Row
' Loop through rows from row 8 to the last used row in column F
For i = 8 To lastRow
' Get the file path from column F
filePath = ws.Cells(i, "F").Value
' Check if the file path is not empty
If filePath <> "" Then
' Check if the file exists
fileExists = Dir(filePath) <> ""
If fileExists Then
On Error GoTo ErrHandler
' Insert object from file, display as icon
Set obj = ws.OLEObjects.Add(Filename:=filePath, _
Link:=False, DisplayAsIcon:=True, _
IconLabel:=Dir(filePath), Left:=ws.Cells(i, "G").Left, _
Top:=ws.Cells(i, "G").Top, Width:=50, Height:=50)
' If no error, proceed
On Error GoTo 0
Else
MsgBox "File not found: " & filePath, vbExclamation
End If
End If
Next i
Exit Sub
ErrHandler:
MsgBox "Error inserting file: " & filePath & vbCrLf & "Error: " & Err.Description, vbCritical
Err.Clear
Resume Next
End Sub