简体   繁体   English

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

[英]How to copy a selection from word to excel using Word VBA

I'm trying to copy word(s) from my word document to a specific cell in the excel workbook. 我正在尝试将单词从我的Word文档复制到excel工作簿中的特定单元格。 I've used Bookmark to find the text i need and copy that then i open the workbook to paste to a specific cell - which is a vlookup reference. 我使用“书签”来查找所需的文本并进行复制,然后打开工作簿以粘贴到特定的单元格-这是vlookup参考。

My code runs but the pasting does not actually occur. 我的代码可以运行,但实际上不会发生粘贴。 I know the copy portion of the code works because when i run up until that point then manually paste the selection, it works just fine. 我知道代码的复制部分是有效的,因为当我运行到该点然后手动粘贴所选内容时,它就可以正常工作。 I've tried multiple options of pasting but nothing has worked so far... 我尝试了多种粘贴选项,但到目前为止没有任何效果...

Selection. Paste

Selection.PasteSpecial (xlPasteAll)

Selection.PasteSpecial (xlPasteValues)

Here is my code: 这是我的代码:

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

I'm not sure what i'm doing wrong but i'd appreciate some guidance on this! 我不确定自己在做什么错,但是对此我将提供一些指导!

Thanks! 谢谢!

Should not need copy/paste: you can assign directly 不需要复制/粘贴:您可以直接分配

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

EDIT: reading from a table cell 编辑:从表单元格读取

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

You need to strip off the two-character "end of cell" marker. 您需要删除两个字符的“单元格结束”标记。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM