как загрузить данные из Excel в слово - PullRequest
0 голосов
/ 05 марта 2019

Я хочу внедрить vba-код в мой текстовый документ: Как загрузить ячейку (1,1) из sheet1 из Excel-документа (скажем, ist Path - это C: \ Test \ Excel.xlsx) в текущий документ Word. В слове document уже существует таблица (2x2). Хочу вставить его в первую ячейку таблицы. Большое спасибо!

1 Ответ

0 голосов
/ 05 марта 2019

В этих решениях используется позднее связывание для передачи Word - Excel


См. Здесь, чтобы узнать больше о позднем и раннем связывании


Шаги для связи из Word в Excel и вставки текста обратно в Word.

Выполните следующие действия:

В Word:

1) Вставьте закладку вячейка таблицы вашего слова и назовите ее «FirstCell»

enter image description here

2) Добавить модуль

enter image description here

3) Скопируйте / вставьте этот код и адаптируйте раздел «<<< Настройка >>>»

enter image description here

Код:

Sub InsertFromWordIntoExcel()

    Dim oExcel As Object
    Dim excelDocument As Object
    Dim bookmarkRange As Range

    Dim bookmarkName As String

    Dim excelWorkbookPath As String
    Dim exceWorkbookName As String
    Dim sheetName As String
    Dim cellContentAddress As String

    ' <<< Customize this >>>
    excelWorkbookPath = "C:\Test\" ' include backslash at the end
    exceWorkbookName = "Excel.xlsx"
    bookmarkName = "FirstCell"
    sheetName = "Sheet1"
    cellContentAddress = "A1"

    ' Check if Excel is already opened
    On Error Resume Next

    Set oExcel = GetObject(, "Excel.Application")

    If Err.Number <> 0 Then
        ' Open a new instance
        Set oExcel = CreateObject("Excel.Application")
        oExcel.Visible = True
    End If

    ' Check if document is already open
    Set excelDocument = oExcel.Workbooks(exceWorkbookName)

    If Err.Number <> 0 Then
        ' Open excel workbook
        Set excelDocument = oExcel.Workbooks.Open(excelWorkbookPath & exceWorkbookName)
    End If

    ' Reset error handling
    Err.Clear
    On Error GoTo 0

    ' Get the bookmark range
    Set bookmarkRange = ThisDocument.Bookmarks(bookmarkName).Range

    ' Insert the cells text
    bookmarkRange.Text = excelDocument.Sheets(sheetName).Range(cellContentAddress).Value

    ' Add the bookmark again
    ThisDocument.Bookmarks.Add bookmarkName, bookmarkRange

End Sub

Альтернативно, чтобы общаться из Excel и вставить текст ячейки в Word.

1) Добавить закладку в Word (как упомянуто выше)

2) Добавить модуль в Excel

3) Скопировать / вставить этот код и адаптировать раздел «<<< Настройка >>>»

Sub InsertFromExcelIntoWord()

    Dim oWord As Object
    Dim wordDocument As Object
    Dim bookmarkRange As Object

    Dim wordDocumentPath As String
    Dim wordDocumentName As String
    Dim bookmarkName As String
    Dim sheetName As String
    Dim cellContentAddress As String

    ' <<< Customize this >>>
    wordDocumentPath = "C:\Test\"  ' include backslash at the end
    wordDocumentName = "Word.docx"
    bookmarkName = "FirstCell"
    sheetName = "Sheet1"
    cellContentAddress = "A1"

    ' Check if Word is already opened
    On Error Resume Next

    Set oWord = GetObject(, "Word.Application")

    If Err.Number <> 0 Then
        ' Open a new instance
        Set oWord = CreateObject("Word.Application")
        oWord.Visible = True
    End If

    ' Check if document is already open
    Set wordDocument = oWord.documents(wordDocumentName)

    If Err.Number <> 0 Then
        ' Open word document
        Set wordDocument = oWord.documents.Open(wordDocumentPath & wordDocumentName)
    End If

    ' Reset error handling
    Err.Clear
    On Error GoTo 0

    ' Get the bookmark range
    Set bookmarkRange = wordDocument.Bookmarks(bookmarkName).Range

    ' Insert the cells text
    bookmarkRange.Text = ThisWorkbook.Sheets(sheetName).Range(cellContentAddress).Value

    ' Add the bookmark again
    wordDocument.Bookmarks.Add bookmarkName, bookmarkRange

End Sub
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...