如何使用Word VBA将选择内容从Word复制到Excel

时间:2019-06-13 01:22:32

标签: excel vba ms-word copy-paste

我正在尝试将单词从我的Word文档复制到excel工作簿中的特定单元格。我使用“书签”来查找所需的文本并进行复制,然后打开工作簿以粘贴到特定的单元格-这是vlookup参考。

我的代码可以运行,但实际上不会发生粘贴。我知道代码的复制部分是有效的,因为当我运行到该点然后手动粘贴所选内容时,它就可以正常工作。我尝试了多种粘贴选项,但到目前为止没有任何效果……

Selection. Paste

Selection.PasteSpecial (xlPasteAll)

Selection.PasteSpecial (xlPasteValues)

这是我的代码:

Sub copypastewordtoexcel()

Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim ExcelWasNotRunning As Boolean
Dim WorkbookToWorkOn As String

ActiveDocument.Bookmarks("Name").Select
Selection.Copy

WorkbookToWorkOn = "C:\Users\arboari\Desktop\Book1.xlsx"

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

Set oWB = oXL.Workbooks.Open(FileName:=WorkbookToWorkOn)

ActiveDocument.Bookmarks("Name").Select
Selection.Copy

For Each oSheet In oXL.ActiveWorkbook.Worksheets
oSheet.Range("A1").Select
Selection.PasteSpecial (xlPasteValue)
Next oSheet

Set oRng = Nothing
Set oSheet = Nothing
Set oWB = Nothing
Set oXL = Nothing

End Sub

我不确定自己在做什么错,但是我希望能对此提供一些指导!

谢谢!

1 个答案:

答案 0 :(得分:3)

不需要复制/粘贴:您可以直接分配

Sub copypastewordtoexcel()

    Dim oXL As Excel.Application
    Dim oWB As Excel.Workbook
    Dim oSheet As Excel.Worksheet
    Dim ExcelWasNotRunning As Boolean
    Dim WorkbookToWorkOn As String

    WorkbookToWorkOn = "C:\Users\arboari\Desktop\Book1.xlsx"

    Set oXL = GetObject(, "Excel.Application")
    Set oWB = oXL.Workbooks.Open(FileName:=WorkbookToWorkOn)

    For Each oSheet In oXL.ActiveWorkbook.Worksheets
            oSheet.Range("A1").Value = ActiveDocument.Bookmarks("Name").Range.Text
    Next oSheet

End Sub

编辑:从表格单元格中读取

txt = ActiveDocument.Tables(1).Cell(1, 1).Range.Text
oSheet.Range("A1").Value = Left(txt, Len(txt)-2)

您需要删除两个字符的“单元格结束”标记。