VBScript激活不带URL的打开Excel电子表格

时间:2017-04-17 20:20:25

标签: excel vbscript

我有一个项目,其中应用程序将用于多个电子表格,命名格式总是不同的。他们希望我从菜单中使用文件→打开打开一个窗口,从桌面上选择电子表格。我已经获得了VBScript代码,但是我无法激活工作簿来收集或输入数据。

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"

我希望Set objWorkbook = ThisWorkbook激活当前工作簿,而不必使用其名称或URL。有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:0)

我想出了如何让它发挥作用。我需要遍历任何打开的Excel电子表格,看看我刚刚打开的那个是否可用。 注意:这仅适用于打开的一个电子表格,即打开对话框打开的电子表格。

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"

这将打开电子表格并在单元格A1中输入“Hello”。