我正在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变量。
答案 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