用户定义的类型未在Word to Excel函数中定义

时间:2018-04-16 13:18:07

标签: vba word-vba

一个不错的用户为我提供了一个更好的解决方案,我已经存在的代码,但在Word中不起作用。我正在尝试在用户单击按钮时打开Excel文档。有多个按钮可以打开同一个文档,但我希望它在文档已经打开时更改工作表而不是文档的另一个实例。以下给出了错误:

  

未定义的用户定义类型

Option Explicit

Public objExcel As Object

Sub Main()


    On Error Resume Next
    Set objExcel = GetObject(, "Excel.Application")
    On Error GoTo 0
    If objExcel Is Nothing Then
        Set objExcel = CreateObject("Excel.Application")
    End If

End Sub

'==================================================================

Public Sub QE1_Click()

    Dim wb As Workbook
    Dim sht As Worksheet

    If objExcel Is Nothing Then
        Main
    End If

    objExcel.Visible = True
    Set wb = objExcel.Workbooks.Open("H:\My Documents\Flowchart to Word\Quality and Environmental management system flowchart.xlsm")

    On Error Resume Next
    Set sht = wb.Worksheets("Project enquiry")
    On Error GoTo 0
    If sht Is Nothing Then
        MsgBox "Workbook doesn't have a sheet named 'Project enquiry'", vbCritical, "Sheet critical error"
    Else
        sht.Activate
    End If

End Sub

不确定为什么这不起作用

1 个答案:

答案 0 :(得分:0)

通常,WorkbookWorksheet是Word的未知对象。因此,您必须使用Excel.来定义它们:

Dim wb As Excel.Workbook
Dim sht As Excel.Worksheet

一般情况下,当VBA代码在Excel中时,wb As Workbook工作得很好,因为Excel是默认环境。但在Word中,您必须明确指定它。确保从VBEditor>添加Microsoft Excel 1N.0 Object Library附加>库:

enter image description here

如果您想让它更容易一些,请将wbsht定义为Object。这被称为"后期绑定"并且有点慢。