[VBA ] 執行階段錯誤'50290'

作者: moon52016 (matrix)   2016-01-02 00:43:23
各位好
最近第一次使用VBA(之前也沒碰過VB),碰上了一些問題:
目的是批量幫excel檔案加密,利用sendkeys的做法((就像機器人一樣...
(程式碼是從網路上修改)
Sub Lock_file()
Dim xlapp As Excel.Application
Dim wbSource As Excel.Workbook
Dim LogFileName As Variant
Dim fname As Variant
Dim x As String, y As String
'取得密碼
x = InputBox("請輸入保護密碼:", "保護密碼")
y = InputBox("請輸入防寫密碼:", "防寫密碼")
Set xlapp = New Excel.Application
'MultiSelect:=True 表示可複選檔案
LogFileName = Application.GetOpenFilename( _
FileFilter:="Excel檔(*.xlsx),*.txt", _
Title:="請選取檔案", MultiSelect:=True)
'判斷使用者是否有選取檔案,或按取消
If VarType(LogFileName) = vbBoolean Then
Exit Sub
End If
xlapp.Visible = True
For Each fname In LogFileName
Set wbSource = xlapp.Workbooks.Open(CStr(fname))
DoEvents
With xlapp
.SendKeys "{F12}", True
Application.Wait (Now + TimeValue("0:00:02"))
.SendKeys "%L", True
Application.Wait (Now + TimeValue("0:00:01"))
.SendKeys "{DOWN}"
Application.Wait (Now + TimeValue("0:00:01"))
.SendKeys "g", True
Application.Wait (Now + TimeValue("0:00:01"))
.SendKeys x, True
Application.Wait (Now + TimeValue("0:00:01"))
.SendKeys "{TAB}", True
Application.Wait (Now + TimeValue("0:00:01"))
.SendKeys y, True
Application.Wait (Now + TimeValue("0:00:01"))
.SendKeys "{ENTER}", True
Application.Wait (Now + TimeValue("0:00:01"))
.SendKeys x, True
Application.Wait (Now + TimeValue("0:00:01"))
.SendKeys "{ENTER}", True
Application.Wait (Now + TimeValue("0:00:01"))
.SendKeys y, True
Application.Wait (Now + TimeValue("0:00:01"))
.SendKeys "{ENTER}", True
Application.Wait (Now + TimeValue("0:00:01"))
.SendKeys "{ENTER}", True
Application.Wait (Now + TimeValue("0:00:01")) '
End With
Next fname
Set wbSource = Nothing 'xlapp.Quit
End Sub
在執行第一個"按F12"之後就會出錯
也測試過了除了第一條按F12以外,其他的都不會有效果
看鍵盤是"numberlock"亮暗亮暗QQ
已經有在網路上搜尋過,有人是說excel還沒準備好,但是還是不知道該怎麼解決
原來的程式碼來源:
http://forum.twbts.com/viewthread.php?tid=2723

Links booklink

Contact Us: admin [ a t ] ucptt.com