导出Word标题书签到Excel UserForm1文本框

时间:2017-09-01 12:17:36

标签: word-vba

我需要VBA代码才能在Excel UserForm1文本框中获取标题书签。请帮助我我有页数,但无法得到这个。我已将代码放在下面,我已尝试过,但它无效。

我收到错误:

Set wbk = ObjExcel.Workbooks.Open("C:\Users\Desktop\Test-2.xlsm")

wst.txtstatementof.Text = "MyBookmark"

提前致谢。

Sub ExportBookmarksToExcel()     Dim bk As Bookmark     昏暗的appXl作为Excel.Application     Dim wbk作为Excel.Workbook     Dim wst作为Excel.Worksheet     Dim x As UserForm1

Set appXl = CreateObject("Excel.Application")
Set wbk = ObjExcel.Workbooks.Open("C:\Users\Desktop\Test-2.xlsm")
With appXl
    .Visible = True
    Set wbk = .Workbooks.Add
    Set wst = wbk.UserForm1
     wst.txtstatementof.Text = "MyBookmark"
  End With

'For each bk In ActiveDocument.Bookmarks
    'lRow = lRow + 1
 '   wst.x.UserForm1.txtstatementof.Text = bk.Name
    'wst.Cells(lRow, 2) = bk.Range.Text
'Next bk
'wst.UsedRange.Columns.AutoFit

 End Sub

1 个答案:

答案 0 :(得分:0)

实际上,你离成功还远远不够。当然,必须失败: -

Set appXl = CreateObject("Excel.Application")
Set wbk = ObjExcel.Workbooks.Open("C:\Users\Desktop\Test-2.xlsm")

您可以看到您的Excel应用程序名为appXl。因此,它无法回复ObjExcel.Workbooks.Open

以下是可行的代码。

Sub ExportBookmarksToExcel()

    ' MS Word variables:
    Dim Bk As Bookmark
    Dim R As Long

    ' MS Excel variables:
    Dim appXl As Excel.Application
    Dim Wbk As Excel.Workbook
    Dim Wst As Excel.Worksheet

    Set appXl = CreateObject("Excel.Application")
    With appXl
        .Visible = True
'        Set Wbk = .Workbooks.Open("C:\Users\Desktop\Test-2.xlsm")
        Set Wbk = .Workbooks.Add
        Set Wst = Wbk.Worksheets(1)
'        Wst.txtstatementof.Text = "MyBookmark"     ' what is "txtstatementof" ?
    End With

    R = 2                                           ' keep Row 1 for captions
    For Each Bk In ActiveDocument.Bookmarks
        Wst.Cells(R, 1) = Bk.Name
        Wst.Cells(R, 2) = Bk.Range.Text
        R = R + 1
    Next Bk
    Wst.UsedRange.Columns.AutoFit

 End Sub