首页 > 解决方案 > Excel VBA 宏 OLEObjects.add 问题

问题描述

编辑:

我开始了一本新的工作簿并撕毁了原始代码以在新的环境中进行测试。即使在这种经过清理的环境中,OLEObjects.add 方法似乎都不起作用。我开始认为这个方法和参数从根本上做了一些我认为他们基于他们的文档所做的事情。我已经包含了下面的解析代码以及附加 .pdf 文件的图片。

Sub AttachDocument()
'create cell location string

Dim celllocation As String
celllocation = ("D6")

'Select the cell in which you want to place the attachment

Range(celllocation).Select

'Get file path
'fpath = Application.GetOpenFilename("All Files,*.*", Title:="Select file")
'If LCase(fpath) = "false" Then Exit Sub
fpath = "C:\Users\Username\Desktop\2019W2.pdf"

'Insert file
Worksheets("Sheet1").OLEObjects.Add Filename:=fpath, Link:=False, DisplayAsIcon:=True, IconFileName:="EXCEL.EXE"
End Sub

<code>在此输入图片说明</code>

我只是不明白为什么参数不起作用。任何帮助表示赞赏。

原帖:

我有将 OLEObject 添加到特定单元格的工作表的代码。它可以工作,但我无法获取 OLEObjects.add 方法的参数来执行任何操作。唯一似乎有效的是“文件名”。无论我如何定义任何其他参数,宏的行为都不会改变;我什至不确定“链接”参数是否正常工作,并且图标始终取决于上传的文件类型,但行为不符合预期(例如,word 文档不显示 word 图标,而是一个大的空白/白色方块)。最终,我想将图标设置为通用图标并定义其大小。我在这里做错了什么?

Sub AttachDocument()

    'Check to make sure there is a selection for table row, if not end macro, also check for selection greater than the number of rows in the table, if yes end macro
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects("RenewablesTable")
    If Range("M3").Value < 1 Then
    ElseIf Range("M3").Value > tbl.DataBodyRange.Rows.Count Then
    Else

        'create cell location string

        Dim cellnum As Integer, celllocation As String
        cellnum = Range("M3").Value + 8
        celllocation = ("M" & cellnum)

        'Select the cell in which you want to place the attachment

        Range(celllocation).Select

        'check if cell already has an object if it does end macro
        If CheckCellforObject(celllocation) > 0 Then

        Else
            'Get file path
            fpath = Application.GetOpenFilename("All Files,*.*", Title:="Select file")
            If LCase(fpath) = "false" Then Exit Sub

            'Insert file
            Worksheets("Renewable Energy").Unprotect "password"
            Worksheets("Renewable Energy").OLEObjects.Add Filename:=fpath, Link:=False, DisplayAsIcon:=True, IconFileName:="excel.exe"
            Worksheets("Renewable Energy").Protect "password"
        End If
    End If
End Sub

标签: excelvba

解决方案


推荐阅读