【发布时间】:2014-11-14 21:24:44
【问题描述】:
感谢您花时间阅读,这里的编程技巧非常简单。我有一个 VBS 脚本,它打开一个 excel 模型,然后调用一个宏从 .txt 文件中提取数据。 excel 中的宏手动运行良好,但在使用脚本时,它会尝试选择 Windows 资源管理器窗口中的所有文件。我相信问题源于打开 .txt 文件,因为我的另外两个 vbs 脚本和 excel 模型在从 .xls 文件中提取数据时工作正常。
我的 VBS 脚本:
Option Explicit
Dim xlApp, xlBook
Set xlApp = CreateObject("Excel.Application")
'xlApp.Visible = True
Set xlBook = xlApp.Workbooks.Open("\\xyzpath\model name.xlsm")
xlApp.Application.Wait(Now + TimeValue("0:00:5"))
xlApp.Application.Run "macroName"
xlBook.Close True
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
WScript.Quit
我的 excel 宏:
Sub updateData()
'Application.ScreenUpdating = False
reloop:
Dim ldate As Date
Dim home, myPath, ldatefile, txtfile As String
Dim ldata As Integer
Dim lrow As Integer
Dim lcol As Integer
Dim s As Variant
ActiveWorkbook.Worksheets("Data").Activate
'Determine end of data set
ldata = Cells.Find("*", [A1], , , xlByColumns, xlPrevious).Column
'Determine date of last data set
ldate = Cells(2, ldata - 14).Value
home = ActiveWorkbook.Name
'Check if up to date, if yes then exit, if no then continue
If ldate >= (Date - 1) Then
Workbooks(home).Worksheets("Dashboard").Activate
Application.ScreenUpdating = True
'MsgBox "Up to date."
Exit Sub
End If
'Specify the path to the folder and open data file
myPath = "\\xyzpath\" & Year(ldate) & "\" & Year(ldate) & " " & Format(ldate + 1, "MM") & "\" & "data" & "\" & "Standard" & "\"
txtfile = "data" & Format(ldate + 1, "YYYYMMDD") & ".txt"
ldatefile = myPath & txtfile
s = Shell("C:\Windows\System32\notepad.exe " & ldatefile, vbNormalFocus)
AppActivate s
'Send keys of actions to Notepad
SendKeys "^a"
SendKeys "^h"
SendKeys " "
SendKeys "{Tab 5}"
SendKeys "~"
SendKeys "{Tab}"
SendKeys "~"
SendKeys "^a", True
SendKeys "^c", True
SendKeys "%{f4}", True
SendKeys "{Tab}", True
SendKeys "~", True
'Copy and paste required data
Application.Wait DateAdd("s", 3, Now())
Workbooks(home).Worksheets("Data").Activate
ActiveSheet.Range(Cells(1, ldata + 1), Cells(50, ldata + 16)).Activate
Application.DisplayAlerts = False
ActiveSheet.Paste
Application.SendKeys "{Enter}", True
Application.DisplayAlerts = True
GoTo reloop
End Sub
所以正如我所提到的,我相信错误在于使用 Shell 打开文本文件时,因为当我以可见的方式运行脚本时,我可以看到它试图抓取 Windows 资源管理器窗口中的所有内容。我尝试了不同的方法来激活 .txt 窗口打开后,但没有运气基于谷歌搜索。如何更改 VBScript 或 excel 宏以正确地将密钥发送到 .txt 应用程序而不是 Windows 资源管理器?非常感谢任何帮助或意见,感谢你们所做的一切,我在使用这些论坛时取得了很多成功。
【问题讨论】: