简体   繁体   English

使用 Worksheetfunction 从 Word VBA 中检索 Excel 上的数据

[英]Retrieve data on Excel from Word VBA using Worksheetfunction

I am trying to automatically fill in tables in a MS word file by retrieving data in various excel tables.我试图通过检索各种 excel 表中的数据来自动填写 MS word 文件中的表。 In order to properly interact with Excel it would be very handy to work with worksheetfunction.为了与 Excel 正确交互,使用工作表功能会非常方便。 Yet since the macro is in MS Word I am getting blocked.然而,由于宏在 MS Word 中,我被阻止了。 Any way to access it?有什么办法可以访问吗? Cheers干杯

Dim src As Workbook
Dim ws As Worksheet

Dim t As String
Dim c As Integer
    
t = ThisDocument.Tables(1).Cell(1, 1).Range.Text
t = Left(t, Len(t) - 1)

Set src = workbooks.Open("https://collab.ext.../asd.xlsx", True, True)
Set ws = src.Worksheets("Data")

c = worksheetfunction.Match(t, ws.Range("A1:AA1"), False)

src.Close
Set src = Nothing

@Tim Williams thanks for your help. @Tim Williams 感谢您的帮助。 Corrected code below:更正代码如下:

Dim oXL As Object
Dim oWB As Workbook
Dim oWS As Worksheet
Dim wbPath As String
Dim t As String
Dim c As Integer

Set oXL = CreateObject("Excel.Application")
oXL.Visible = False

wbPath = "https://collab.ext...asd.xlsx"
    
t = ThisDocument.Tables(1).Cell(1, 1).Range.Text
t = Left(t, Len(t) - 2)

Set oWB = oXL.workbooks.Open(wbPath, True, True)
Set oWS = oWB.Sheets("Data")
    
c = oXL.worksheetfunction.Match(t, oWS.Range("A1:AA3"), False)

oXL.ActiveWorkbook.Close SaveChanges:=False
oXL.Application.Quit
Set oXL = Nothing
Set oWB = Nothing
Set oWS = Nothing

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

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