期待VBA完成的指令為:
寫出的代碼無法成功運作,經逐行運行確認,代碼運行下列停止
' Send Alt+N to select "Save As" option
SendKeys "%n"
並停止於PDF存檔畫面,無法順利於對話框中寫入檔案名稱(excel檔案中對應A欄位的客戶ID)並按下存檔。(無法順利完成指令6)
只能手動輸入檔案名稱即按下存檔,代碼才會繼續運行,驗證下一個號碼。
想請教大神們我該如何修改代碼,或是有什麼其他建議呢?
完整VBA 如下:
Sub VerifyPermitNumbers()
Dim ie As Object
Dim permitNumber As String
Dim custId As String
Dim lastRow As Long
Dim i As Long
' Get the last non-empty cell in column B
lastRow = Cells(Rows.Count, "B").End(xlUp).Row
' Open the website and fill out the form
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
ie.Navigate "https://efile.boe.ca.gov/boewebservices/verification.jsp?action=SALES"
' Wait for the website to load
Do While ie.Busy Or ie.ReadyState <> 4
DoEvents
Loop
' Loop through each cell in column B
For i = 2 To lastRow
' Get the permit number and customer ID
permitNumber = Cells(i, "B").Value
custId = Cells(i, "A").Value
' Select "SITSUT" and enter the permit number
ie.Document.getElementById("d-3").Value = "SITSUT"
ie.Document.getElementById("d-4").Value = permitNumber
' Click the Search button
ie.Document.getElementById("d-5").Click
' Wait for the search results page to load
Do While ie.Busy Or ie.ReadyState <> 4
DoEvents
Loop
' Save the web page as a PDF file
Dim pdfPath As String
pdfPath = "C:\Users\Desktop\test\" & custId & ".pdf"
ie.ExecWB 6, 2, pdfPath, 0
' Wait for the save dialog to appear
Do While ie.Busy Or ie.ReadyState <> 4
DoEvents
Loop
' Send Alt+N to select "Save As" option
SendKeys "%n"
' Wait for the file name input field to appear
Application.Wait Now + TimeValue("0:00:10")
' Send the file name and press Enter
SendKeys pdfPath & "~"
' Wait for the PDF to be saved
Application.Wait Now + TimeValue("0:00:05")
Next i
' Close the Internet Explorer window
ie.Quit
MsgBox "All permit numbers have been verified."
End Sub
原本的VBA沒有指定要發送按鈕的訊息給哪個視窗,所以會停留在PDF存檔畫面。此外,在存檔後也沒有等待存檔完成再繼續下一步驟,所以可能會出現存檔不完整的情況。
從' Wait for the save dialog to appear這行開始修改看看。
' Wait for the save dialog to appear
Application.Wait Now + TimeValue("0:00:10")
' Send the file name and press Enter
Application.SendKeys pdfPath & "{ENTER}"
' Wait for the PDF to be saved
Application.Wait Now + TimeValue("0:00:05")
Next i
' Close the Internet Explorer window
ie.Quit
MsgBox "All permit numbers have been verified."
End Sub
或是
' Wait for the save dialog to appear
Application.Wait Now + TimeValue("0:00:10")
' Send the file name and press Enter
SendKeys pdfPath & "~"
' Wait for the PDF to be saved
Application.Wait Now + TimeValue("0:00:05")
' Go back to search page
ie.GoBack
' Wait for the page to load
Do While ie.Busy Or ie.ReadyState <> 4
DoEvents
Loop
Next i
' Close the Internet Explorer window
ie.Quit
MsgBox "All permit numbers have been verified."
End Sub