繁体   English   中英

是否可以使用 VBA 将变量从 MS Word 传递到 Excel?

[英]Is it possible to pass a variable from MS Word to Excel with VBA?

我有一种情况,我需要通过宏将变量从 Word 传递给 Excel。 推理有点复杂,但基本上我想以此作为创建自定义索引的一种方式。 我指出,以防可能有更简单的方法来创建索引。 此特定索引是根据在其中找到单词或短语的段落而不是页码创建的。 在 Word 中似乎没有办法做到这一点。

因此,我想突出显示单词或短语,按我的宏组合(或添加右键单击菜单项来执行此操作)将突出显示的文本分配给变量,然后将其发送到三个打开的工作表之一(将有 3部分到索引)并将其添加到电子表格的底行。 从那里我需要按字母顺序排列列表并将所有相同的短语组合到一个单元格中。

I know how to send items from Excel to Word, but when I try to research the idea of sending from Word to Excel all I can find are examples of Excel retrieving something from Word and returning it back to Excel. 这不适用于我正在做的事情。 将有数千个索引条目(在我组合它们之前)。

如果无法将 go 直接从 Word 到 Excel 那么我想我可以将选定的文本发送到另一个文档,但我不知道该怎么做。

请帮忙!

我不明白为什么你需要在 Word 中的 Excel 中工作,但我准备了一段代码来向你展示如何(轻松)访问 Excel object 并使用它的对象:

Sub testWorkingInExcel()
 Dim objEx As Excel.Application, wb As Excel.Workbook, W As Excel.Workbook, sh As Excel.Worksheet
 Dim lastEmptyRow As Long, boolFound As Boolean
 
 On Error Resume Next
 Set objEx = GetObject(, "Excel.Application") 'find Excel open session if any
  If Err.Number <> 0 Then
    Err.Clear: On Error GoTo 0
    Set objEx = CreateObject("Excel.Application")
    Set wb = objEx.Workbooks.Open("Workbook full name")
  Else
    For Each W In objEx.Workbooks
        If W.Name = "Needed workbook" Then
            Set wb = W: boolFound = True: Exit Sub
        End If
    Next
    If Not boolFound Then Set wb = objEx.Workbooks.Open("Workbook full name")
  End If
 On Error GoTo 0
 Set sh = wb.Worksheets("NeededSheet")
 lastEmptyRow = sh.Range("A" & sh.Rows.Count).End(xlUp).Row
 'Now, you have the last empty row of the needed page and you can do
 'whatever you could do directly in Excel...
End Sub

暂无
暂无

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

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