VBScript打开excel来调用宏失败

时间:2014-11-14 21:24:44

标签: excel vba vbscript

感谢您花时间阅读,非常了解编程技巧。我有一个VBS脚本打开一个excel模型,然后调用宏从.txt文件中提取数据。 excel中的宏可以手动运行,但在使用脚本时,它会尝试选择Windows资源管理器窗口中的所有文件。我认为这个问题源于打开.txt文件,因为当从.xls文件中提取数据时,我的另外两个vbs脚本和excel模型工作正常。

我的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资源管理器?非常感谢任何帮助或意见,感谢大家所做的一切,我利用这些论坛获得了很多成功。

1 个答案:

答案 0 :(得分:0)

首先:使用SendKeys 第二:使用SendKeys

使用FileSystemObject从文件中读取文字:

...
Set fso = CreateObject("Scripting.FileSystemObject")

ldatefile = fso.BuildPath(myPath, txtfile)
Set f = fso.OpenTextFile(ldatefile)
Do Until f.AtEndOfStream
  l   = f.Line
  v = Split(Replace(f.ReadLine, " ", ""), vbTab)
  For i = 0 To UBound(v)
    Workbooks(home).Worksheets("Data").Cells(l, ldata+i+1).Value = v(i)
  Next
Loop
f.Close
...