VBScript Activate open Excel spreadsheet without URL

大憨熊 提交于 2020-01-25 21:45:09

问题


I have a project where the application will be used for multiple spreadsheets and naming formats are always going to be different. They want me to use File → Open from the menu to open a window where they select the spreadsheet from their desktop. I've got the VBScript code for that, but I can't activate the workbook to gather, or enter, data.

WShell.SendKeys "%FO"

objExcel.Wait (Now + TimeSerial(0, 0, 3))

For i = 1 to 3
   WShell.SendKeys "+{TAB}"
Next

WShell.SendKeys "{HOME}"
WShell.SendKeys "D"
WShell.SendKeys "{ENTER}"

MsgBox "Please select the file you want to open, then click OK to continue.", _
    vbOKOnly+vbSystemModal, "Open File"

WShell.SendKeys "{ENTER}"

Set objWorkbook = ThisWorkbook

objWorkbook.Sheets(1).Activate
objWorkbook.Sheets(1).Cells(1, 1).Value = "Hello"

I want Set objWorkbook = ThisWorkbook to activate the current workbook without having to use its name or URL. Can someone help me with this?


回答1:


I figured out how to get it to work. I needed to cycle through any open Excel spreadsheets to see if the one I just opened was available. NOTE: This only works for one spreadsheet open, which is the one opened by the Open dialog box.

WShell.SendKeys "%FO"

objExcel.Wait (Now + TimeSerial(0, 0, 3))

For i = 1 to 3
    WShell.SendKeys "+{TAB}"
Next

WShell.SendKeys "{HOME}"
WShell.SendKeys "D"
WShell.SendKeys "{ENTER}"

MsgBox "Please select the file you want to open, then click OK to continue.", _
vbOKOnly+vbSystemModal, "Open File"

WShell.SendKeys "{ENTER}"

On Error Resume Next
   Set objExcel = GetObject(,"Excel.Application")
   If Err.Number <> 0 Then ShowError ("Macro failed to get Excel object.")
On Error GoTo 0

objExcel.Wait (Now + TimeSerial(0, 0, 1))

For Each WB In objExcel.Workbooks
    Set objWorkbook = WB
Next

objWorkbook.Sheets(1).Activate
objWorkbook.Sheets(1).Cells(1, 1).Value = "Hello"

This will take the open spreadsheet and enter "Hello" in cell A1.



来源:https://stackoverflow.com/questions/43458987/vbscript-activate-open-excel-spreadsheet-without-url

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!