从excel中提取价值而无需激活工作簿

时间:2019-01-09 06:45:32

标签: excel vba ms-word word-vba

我正在MS Word上工作,需要使用以下代码从Excel Workbook提取数据:

它将在工作簿中Find TICKER,如果找到,则将使用工作簿中的值设置SECTOR变量。

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

If MyXL.ActiveWorkbook.NAME = "LIST.xlsm" Then
Set eXwb = GetObject("C:\Users\dell\Desktop\WEBD\LIST.xlsm")
Else
Set eXwb = MyXL.Workbooks("LIST.xlsm")
eXwb.Activate
End If

eXwb.Worksheets("Sheet4").Cells.Find(What:=TICKER).Offset(0, 2).Activate ' Is there any oneline code to find and set SECTOR variable without activating workbook
Set SECTOR = eXwb.Application.ActiveCell

是否有可能可以在不激活eXwb工作簿的情况下提取数据。 是否有任何一行代码可以在不激活工作簿的情况下查找和设置SECTOR变量。

1 个答案:

答案 0 :(得分:1)

只需删除行eXwb.Activate。同时从.Activate中删除eXwb.Worksheets("Sheet4").Cells.Find(What:=TICKER).Offset(0, 2).Activate,直接使用范围

您的代码可以写为

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

If MyXL.ActiveWorkbook.Name = "LIST.xlsm" Then
    Set eXwb = GetObject("C:\Users\dell\Desktop\WEBD\LIST.xlsm")
Else
    Set eXwb = MyXL.Workbooks("LIST.xlsm")
End If

Dim SECTOR As Object '~~> Code is run from MS Word

Set SECTOR = eXwb.Worksheets("Sheet4").Cells.Find(What:=TICKER)

'~~> Check if .Find returned something
If Not SECTOR Is Nothing Then
    Set SECTOR = SECTOR.Offset(, 2)
    MsgBox SECTOR.Value
Else
    MsgBox "Ticker " & TICKER & " was not found"
End If