I have this macro that pulls out data from a website. I get the inputs from a user-from. It works with no error but IE won't close and sucks up all of the memory. Is something else needed rather than IE.Quit?
This is the sub. As you can see I close IE at the end.
Public Cancel As Boolean
Sub USGD()
Dim IE As Object
Dim iWsh As Worksheet
Dim link As String
Dim sDate As String
Dim eDate As String
Dim StationID As String
Cancel = False
With USGS
.StartUpPosition = 0
.Left = Application.Left + (0.5 * Application.Width) - (0.5 * .Width)
.Top = Application.Top + (0.5 * Application.Height) - (0.5 * .Height)
.Show
End With
If Cancel = True Then
Unload USGS
Exit Sub
End If
With ActiveWorkbook
Set iWsh = .Sheets.Add(After:=.Sheets(.Sheets.Count))
End With
iWsh.Activate
iWsh.Range("A1").Select 'I know this is not efficient but works fine
StationID = USGS.TextBox1.Text
'StationID = InputBox("Please enter the station ID")
'sDate = InputBox("Please enter START date in this format: 'yyyy-mm-dd'")
'eDate = InputBox("Please enter END date in this format: 'yyyy-mm-dd'")
sDate = Format(USGS.TextBox2.Text, "yyyy-mm-dd")
eDate = Format(USGS.TextBox3.Text, "yyyy-mm-dd")
link = "https://waterdata.usgs.gov/ & _
StationID & sDate & eDate
Unload USGS
Set IE = CreateObject("InternetExplorer.Application")
With IE
.Visible = False
.Navigate link 'URL
Do Until .ReadyState = 4: DoEvents: Loop
.ExecWB 17, 0 '// SelectAll
.ExecWB 12, 2 '// Copy selection
End With
iWsh.PasteSpecial Format:="Text", link:=False, DisplayAsIcon:=False
Range("A1").Select
IE.Quit
Set IE = Nothing
Set iWsh = Nothing
End Sub
And this is the user-form: I didn't have this problem while using Input-Box so I am guessing, it has something to do with the user-form. This only happens when user closes the user-form.
Private Sub ToggleButton1_Click()
Me.Hide
Cancel = True
End Sub
Private Sub OK_Click()
Me.Hide
End Sub
Note: If the user cancel, it would not even open the IE and exits the sub right after.
But if user closes the form, it does open IE, and doesn't set the Cancel to be True which is the condition to exit the sub.
Update: Expert-Exchange covered the issue but never came up with an actual solution.
Update-2: Closing all instances of IE is not an option.
This is how user-form is set up now:
OK so I am unable to replicate the error, so there are two things you should try:
Reboot your computer and verify the error continues. If not, problem solved.
Recreate the UserForm & code in a new, blank workbook, and see if the error continues. If not, problem solved.
(Sometimes Workbooks, and/or UserForms become corrupted)
I also re-factored the code a little bit, which you might consider even if one of the above suggestions solves the problem. It just cleans it up a little bit and makes it more purposeful.
In a standard module, place the following code:
The USGD procedure displays the userform and unloads it. A separate procedure named GetData will do the work in IE and add the worksheet, etc. The GetData procedure is only executed if the user clicks on the "OK" button on the form. Therefore, the "X"/cancel button will allow the user to close the form.
Option Explicit
Sub USGD()
'Procedure displays the userform for the user
Dim USGSForm As New USGS
With USGSForm
.StartUpPosition = 0
.Left = Application.Left + (0.5 * Application.Width) - (0.5 * .Width)
.Top = Application.Top + (0.5 * Application.Height) - (0.5 * .Height)
.Show
End With
Unload USGSForm
End Sub
Sub GetData(StationID As String, sDate As String, eDate As String)
'This procedure queries the InternetExplorer for the values from UserForm
Dim iWsh As Worksheet
Dim link As String
Dim IE As Object
sDate = Format(sDate, "yyyy-mm-dd")
eDate = Format(eDate, "yyyy-mm-dd")
link = "https://waterdata.usgs.gov/nwis/dv?cb_00060=on&format=rdb&site_no=" & _
StationID & "&referred_module=sw&period=&begin_date=" & sDate & "&end_date=" & eDate
Set IE = CreateObject("InternetExplorer.Application")
With IE
.Visible = False
.Navigate link 'URL
Do Until .ReadyState = 4: DoEvents: Loop
.ExecWB 17, 0 '// SelectAll
.ExecWB 12, 2 '// Copy selection
.Quit
End With
With ActiveWorkbook
Set iWsh = .Sheets.Add(After:=.Sheets(.Sheets.Count))
End With
iWsh.PasteSpecial Format:="Text", link:=False, DisplayAsIcon:=False
Application.GoTo iWsh.Range("A1")
End Sub
In your UserForm module, place the following code:
This is the code for the "OK" button, which takes the values from TextBoxes on the form and sends those to the GetData procedure. Note the Select Case logic which will exit the procedure early if any of the parameters are empty, so it will not call GetData.
Private Sub OK_Click()
Dim id As String, sDate As String, eDate As String
'Get values from the form
id = Me.TextBox1.Value
sDate = Me.TextBox2.Value
eDate = Me.TextBox3.Value
'Hide the form
Me.Hide
'If ANY required parameter is blank, this results in malformed URL so exit the procedure
Select Case vbNullString
Case id, sDate, eDate
MsgBox "You left some parameter blank, no query will be performed.", vbInformation
GoTo EarlyExit
Case Else
'Send values to the procedure that queries IE
Call GetData(id, sDate, eDate)
End Select
EarlyExit:
End Sub
I found a workaround but not a good answer. Also, does not explain why that happens.
I changed my user-form so the user cannot close it. Also set the initial value of Cancel to be True
Cancel = True
and when the use pushes OK it will be set to false. Look below for the user form code:
Private Sub ToggleButton1_Click()
End Sub
Private Sub OK_Click()
Me.Hide
Cancel = False
End Sub
Obvious downside of this is that users cannot close the user-form; they have to hit OK. This won't cause an error. I just can add a condition that if one of the text boxes was empty then exit the sub. Something like below;
If sDate = "" Or eDate = "" Or StationID = "" Then GoTo 92
'. Rest of ...
'. My ...
'. Code ...
92:
Set IE = Nothing
End Sub
Related
I have a userform. The idea is to check if there are any 'True' values in column(15) in 'Admin' sheet. If there is at least a single 'True' value, then the userform will remain open and continue its operation.
However, if there is not a single 'True' found, then the userform will display a message and close the userform automatically.
Private Sub Userform_initialize()
Dim LR As Long
LR = Sheets("Project_Name").Cells(Rows.Count, "B").End(xlUp).Row
With Worksheets("Admin")
For i = 7 To LR
If .Cells(i, 15) = "True" Then
Exit For
Else
MsgBox ("No values found")
Exit For
Unload Me
End If
Next i
End With
''' more code'''
End Sub
Everything on my userform works as expected, except for the fact I am unable to make it close itself automatically. I.e. Unload Me is not working.
Any advice?
You should check your criteria before you even display the UserForm. You can add this as a condition wherever you are calling the UserForm. No need to open the form just to immediately close it when you can check before-hand.
On the first instance of True, the UserForm will open, and exit the sub. If the loop completes (finds no True values), the sub will proceed to your MsgBox
Sub OpenForm
With Worksheets("Admin")
For i = 7 To LR
If Cells(i,15) = "True" then
Userform.Show
Exit Sub
End If
Next i
End With
MsgBox "No Values Found"
End Sub
Please look at your code; you have put Unload Me is after Exit For
'Here is something for you to ponder on .........
'Public enum type to add a set of particular vbKeys to the standard key set
Public Enum typePressKeys
vbNoKey = 0
vbExitTrigger = -1
vbAnswerKey = 100
vbLaunchKey = 102
vbPrevious = 104
vbNext = 106
vbSpecialAccessKey = 108
End Enum
Public Sub doSomethingWithMyUserform()
Dim stopLoop As Boolean, testVal As Boolean, rngX As Range, LR As Long
LR = ThisWorkbook.Sheets("Project_Name").Cells(Rows.Count, "B").End(xlUp).Row
Set rngX = ThisWorkbook.Worksheets("Admin")
testVal = False
With rngX 'Your sub can do the check here
For i = 7 To LR
If .Cells(i, 15) = "True" Then
testVal = True
Exit For
End If
Next i
End With
If testVal Then
Load UserForm1
With UserForm1
.Caption = "Something"
.Tag = vbNoKey
.button_OK.SetFocus 'Assuming you have a OK button on Userform1
End With
UserForm1.Show
stopLoop = False
Do
If UserForm1.Tag = vbCancel Then
'Do something perhaps
Unload UserForm1
stopLoop = True
ElseIf UserForm1.Tag = vbOK Then
'Do something specific
Unload UserForm1
stopLoop = True
Else
stopLoop = False
End If
Loop Until stopLoop = True
else
MsgBox "No values found"
End If
'Here you can close the way you want
Set rngX = Nothing
End Sub
enter code here
I need help with a code that was written for me. The code is below. I works find perhaps 70% of the time, but every approx 20 rows it throws up
Runtime Error 70: Permission Denied
What would cause this, and is there any fix for it? Also, How can I change the code to skip any errors like this (or similar) and just move onto the next row.
Debugger throws up the line: If btn.ID = "gs_hdr_tsb" Then
The full script is below.
Dim ie As Object
Private Sub CommandButton1_Click()
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
ie.Navigate TextBox1.Text
Do
DoEvents
Loop Until ie.readystate = 4
Application.Wait (Now + TimeValue("00:00:02"))
End Sub
Private Sub CommandButton2_Click()
Dim i As Long
Dim prfl As String
Dim ws As Worksheet
Set ws = ActiveSheet
Dim INPTTG, btn As Object
Dim Profile_link As String
Dim H3tg As Object
Dim iedata As Object
If iedata Is Nothing Then
Set iedata = CreateObject("InternetExplorer.Application")
End If
iedata.Visible = True
For i = TextBox2.Text To TextBox3.Text
prfl = ws.Range("E" & i).Value
For Each INPTTG In ie.document.getelementsbytagname("input")
If INPTTG.classname = "gs_in_txt" Then
INPTTG.Value = ""
INPTTG.Value = prfl
Exit For
End If
Next INPTTG
'button
Application.Wait (Now + TimeValue("00:00:02"))
For Each btn In ie.document.getelementsbytagname("button")
If btn.ID = "gs_hdr_tsb" Then
btn.Click
Do
DoEvents
Loop Until ie.readystate = 4
Application.Wait (Now + TimeValue("00:00:02"))
End If
Next btn
'prfl
For Each H3tg In ie.document.getelementsbytagname("h3")
If H3tg.classname = "gsc_oai_name" And VBA.Trim(H3tg.innertext) = prfl Then
Call GetData(H3tg.getelementsbytagname("a").Item(0).href, iedata, i)
Exit For
End If
Next H3tg
TextBox2.Text = i
Next i
MsgBox "Completed"
iedata.Quit
Set iedata = Nothing
Application.DisplayAlerts = False
ThisWorkbook.Save
End Sub
Any help would be very appreciated.
Try this one.
Dim ie As Object
Private Sub CommandButton1_Click()
On error go to ErrMsg
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
ie.Navigate TextBox1.Text
Do
DoEvents
Loop Until ie.readystate = 4
Application.Wait (Now + TimeValue("00:00:02"))
ErrMsg:
End Sub
Private Sub CommandButton2_Click()
Dim i As Long
Dim prfl As String
Dim ws As Worksheet
Set ws = ActiveSheet
Dim INPTTG, btn As Object
Dim Profile_link As String
Dim H3tg As Object
Dim iedata As Object
On error go to msgErr
If iedata Is Nothing Then
Set iedata = CreateObject("InternetExplorer.Application")
End If
iedata.Visible = True
For i = TextBox2.Text To TextBox3.Text
prfl = ws.Range("E" & i).Value
For Each INPTTG In ie.document.getelementsbytagname("input")
If INPTTG.classname = "gs_in_txt" Then
INPTTG.Value = ""
INPTTG.Value = prfl
Exit For
End If
Next INPTTG
'button
Application.Wait (Now + TimeValue("00:00:02"))
For Each btn In ie.document.getelementsbytagname("button")
If btn.ID = "gs_hdr_tsb" Then
btn.Click
Do
DoEvents
Loop Until ie.readystate = 4
Application.Wait (Now + TimeValue("00:00:02"))
End If
Next btn
'prfl
For Each H3tg In ie.document.getelementsbytagname("h3")
If H3tg.classname = "gsc_oai_name" And VBA.Trim(H3tg.innertext) = prfl Then
Call GetData(H3tg.getelementsbytagname("a").Item(0).href, iedata, i)
Exit For
End If
Next H3tg
TextBox2.Text = i
Next i
MsgBox "Completed"
iedata.Quit
Set iedata = Nothing
Application.DisplayAlerts = False
ThisWorkbook.Save
MsgErr:
End Sub
There are several answers here on StackOverflow about this VB Error. Each answer or situation is unique in reality - although each existing answer states a different potential root cause (file permissions, folder permissions, name reuse, ranges, etc).
I would recommend narrowing down the root-cause by double clicking on the side of the stating function/code in order to mark a breakpoinnt (looks like a red dot) (Alternatively, you can right click on the line of the code - Select the Toggle and then Breakpoint).
Next, run your code, and it will stop in your breakpoint. You can then Step-Into/Over/Out your code and essentially find the line of code that is responsible for throwing your error code. (Step Into is F8, Step over is Shift+F8 ((Go To the Debug top menu to see more options)))
Once you identified the responsible line of code - you can start looking further.
In my case scenario, I was using a protected variable name "Date" (look into variable names). Once I renamed it to something else, the problem was fixed.
One possible cause of this error (as was my case) is an antivirus/antimalware program blocking certain libraries. Try temporarily disabling all antivirus/antimalware programs and test your script again. In my case, Malwarebytes
In MalWare bytes, you can disable this setting by going to:
Security > Advanced Settings > Application Hardening [tab]
On the row called "Disable Loading of VBScript Libraries", un-check the checkbox under "MS Office".
I am using the following vba code in a workbook open event:
Private Sub Workbook_Open()
On Error GoTo Message
Application.AskToUpdateLinks = False
ThisWorkbook.UpdateLinks = xlUpdateLinksNever
ActiveSheet.DisplayPageBreaks = False
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim currentTime As Date
currentTime = DateAdd("s", 10, Now)
Call CurUserNames
Application.OnTime currentTime, "SaveFile"
Exit Sub
Message:
Application.DisplayAlerts = False
Exit Sub
End Sub
I also have this code in a module:
Public Sub SaveFile()
On Error GoTo Message
ThisWorkbook.Save
Dim currentTime As Date
currentTime = DateAdd("s", 10, Now)
Application.OnTime currentTime, "SaveFile"
Exit Sub
Message:
Application.DisplayAlerts = False
Exit Sub
End Sub
What I am trying to do is automatically save my workbook every 10 seconds.
This works.
However, something quite annoying I've noticed happens. If a user has this workbook open in the background and is working on another excel workbook then this workbook will activate and display on top of the other workbook when saving.
This can be quite annoying for the user.
Is there a way I can get my workbook to save without activating the workbook?
P.S:
For some unknown reason, this also causes the workbook to reopen when its been closed.
EDIT:
List active users in workbook code:
Sub CurUserNames()
Dim str As String
Dim Val1 As String
str = "Users currently online:" & Chr(10)
For i = 1 To UBound(ThisWorkbook.UserStatus)
str = str & ThisWorkbook.UserStatus(i, 1) & ", "
Next
Val1 = DeDupeString(Mid(str, 1, Len(str) - 2))
Worksheets("Delivery Tracking").Range("F4").Value = Val1
End Sub
Function DeDupeString(ByVal sInput As String, Optional ByVal sDelimiter As String = ",") As String
Dim varSection As Variant
Dim sTemp As String
For Each varSection In Split(sInput, sDelimiter)
If InStr(1, sDelimiter & sTemp & sDelimiter, sDelimiter & varSection & sDelimiter, vbTextCompare) = 0 Then
sTemp = sTemp & sDelimiter & varSection
End If
Next varSection
DeDupeString = Mid(sTemp, Len(sDelimiter) + 1)
End Function
Users of a shared workbook can see Who has this workbook open now: just by going to the Review tab in the Ribbon and click the Shared Workbook icon in the Changes group. This will open the Shared Workbook dialog box, in it the tab Editing' shows *Who has this workbook open now:`*. Additionally the tab 'Advance' can be used to update the settings dealing with:
Track changes
Update changes
Conflicting changes between users
Include in personal view
Th9is example comes from How can I get list of users using specific shared workbook?
It is a little overkill. It creates a new workbook to put the users name in. But you can modify it to put the names in whatever sheet and whatever cells you want.
Put it in the sheet module under the selection change module. Then it will update every time the user moves to a different cell. If it is open and he's not at his desk - it doesn't do anything.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
End Sub
At the bottom is the code from the above link that you can modify to suit your own needs. It will be 1000 times better than saving a workbook every ten seconds. Which can actually take 3 or 4 seconds itself.
If you don't want to use selection change in the worksheet module then you could put your code into the workbook module Private Sub Workbook_Open()
and put it on a timer to run every 10 seconds. It will only take a fraction of a second instead of several seconds.
users = ActiveWorkbook.UserStatus
With Workbooks.Add.Sheets(1)
For row = 1 To UBound(users, 1)
.Cells(row, 1) = users(row, 1)
.Cells(row, 2) = users(row, 2)
Select Case users(row, 3)
Case 1
.Cells(row, 3).Value = "Exclusive"
Case 2
.Cells(row, 3).Value = "Shared"
End Select
Next
End With
When a user opens my VBA program it hides all Excel's command bar's and whatnot so it looks as if my program is not running in Excel at all. Since this action will take place across all instances of Excel I found some code that will check if other programs are open, and if so save my program as a temp file and reopen it in a new instance of Excel.
The problem though is when it opens it doesn't fire off the Workbook_Open event. As a temporary fix I've put a button on a spreadsheet that runs the macro to launch the program but I need to do better than this. Can you take a look at the code at this site and let me know why the Workbook_Open event is not firing? (as you can see I've already asked the forum twice for help on it with no response).
Updated with code
The code that duplicates the program and opens the new instance is in the UserForm section of code at the bottom.
Placed in ThisWorkbook:
Private Sub Workbook_Open()
Set clsAPP.XLAPP_ORIG = Application
If Application.UserControl Then
If Application.Workbooks.Count > 1 Then
Application.Visible = False
DoEvents
frmCreateReplicant.Show vbModal
End If
End If
Call ThisWorkbook_CompleteOpening
End Sub
Placed in standard module:
Option Explicit
Public XLAPP_Copy As New Excel.Application, _
clsAPP As New clsXLApp
Public Sub ThisWorkbook_Open()
Dim intMaxRow As Integer
If Application.Workbooks.Count > 1 Then
Application.Visible = False
DoEvents
frmCreateReplicant.Show vbModal
'Call ThisWorkbook_CompleteOpening
Else
ThisWorkbook_CompleteOpening
End If
ThisWorkbook.Saved = True
Delay
End Sub
Sub ThisWorkbook_CompleteOpening(Optional Fake)
'MsgBox "...Any other OnOpen code here..."
End Sub
Function Delay(Optional SecondFraction As Single = 0.2)
Dim sngTimeHack As Single, dtmDate As Date
sngTimeHack = Timer: dtmDate = Date
If sngTimeHack + SecondFraction < 86400 Then
Do
DoEvents
Loop While Timer < (sngTimeHack + SecondFraction)
Else
If dtmDate = Date Then
Do
DoEvents
Loop While dtmDate = Date
End If
sngTimeHack = (sngTimeHack + SecondFraction) - 86400
If DateAdd("d", 1, dtmDate) = Date Then
Do
DoEvents
Loop While Timer < sngTimeHack
End If
End If
End Function
Function KillMeBasic()
With ThisWorkbook
.Saved = True
.ChangeFileAccess Mode:=xlReadOnly
Kill .FullName
.Close False
End With
End Function
Placed in class module:
Option Explicit
Public WithEvents XLAPP_ORIG As Application
Private Sub XLAPP_ORIG_NewWorkbook(ByVal Wb As Workbook)
Wb.Close False
MsgBox MsgTxt(1), 64, vbNullString
End Sub
Private Sub XLAPP_ORIG_WorkbookOpen(ByVal Wb As Workbook)
If Not Wb.Name = ThisWorkbook.Name Then
Wb.Close False
MsgBox MsgTxt(2), 64, vbNullString
End If
End Sub
Private Function MsgTxt(Opt As Long) As String
Select Case Opt
Case 1
MsgTxt = _
"Sorry, you cannot create a new workbook here." & vbCrLf & _
"You can start a new instance of Excel by..."
Case 2
MsgTxt = _
"You cannot open another workbook here. You" & vbCrLf & _
"can open another workbook by first..."
End Select
End Function
Placed in UserForm:
Private Sub UserForm_Activate()
Dim strThisWorkbookFullname As String
Dim wbMeCopy As Workbook
Delay 0.05
Set XLAPP_Copy = CreateObject("Excel.Application")
strThisWorkbookFullname = ThisWorkbook.FullName
Application.DisplayAlerts = False
ThisWorkbook.SaveAs Filename:=ThisWorkbook.Path & "\00000000001.xls", _
Password:="NeedKilled", AddToMru:=False
Application.DisplayAlerts = True
Do While ThisWorkbook.Saved = False
Loop
Delay 0.2
XLAPP_Copy.Workbooks.Open Filename:=strThisWorkbookFullname, AddToMru:=False
Do
On Error Resume Next
Set wbMeCopy = XLAPP_Copy.Workbooks(1)
On Error GoTo 0
Loop While wbMeCopy Is Nothing
Set wbMeCopy = Nothing
Delay 0.1
Application.Visible = True
XLAPP_Copy.Visible = True
Unload Me
Delay
Call KillMeBasic
End Sub
Private Sub UserForm_Initialize()
With Me
.BackColor = &H0&
.Caption = ""
.ForeColor = &H0&
.Height = 123
.Width = 240
With .lblMsg
.BackColor = &H0&
.Caption = String(2, vbCrLf) & _
"Please wait, I am protecting the program..."
With .Font
.Name = "Century Gothic"
.Size = 10
End With
.ForeColor = &HC000C0
.Height = 90
.Left = 6
.TextAlign = fmTextAlignCenter
.Top = 6
.Width = 222
End With
End With
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu _
Then Cancel = True
End Sub
This works to hide the Ribbon/command bars (although the File or Backstage menu is still present, thought I think you may be able to disable this I have not tried yet), if you are hiding other stuff like the StatusBar, etc., it may not be enough to solve your problem, but here it is anyways.
Using the CustomUI editor, open the XLSM file.
Note: The XLSM file should not be open in any instance of Excel when you are opening it through the Custom UI Editor. If it is open in Excel, the modifications to the XML will not be saved properly.
Once you have the file open in the CustomUI Editor, you'll see this:
From the menu, Insert Office 2010 Custom UI Part:
Then copy and paste this XML:
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui">
<ribbon startFromScratch="true" />
</customUI>
Finally, save & close the file through the CustomUI Editor, then re-open in Excel. You should see that the while this file/workbook is active, the ribbon does not exist.
But, if you switch to another Workbook file, the ribbon will re-appear while that file is active.
The startFromScratch property makes it so that when this Workbook has focus, the only ribbon elements which are displayed to the user, within the Application's window, are those which are defined within the XML, which as you can probably gather in the snippet above, are none.
This also entirely avoids the need to try and open copies of the file in a new instance of Excel Application, which (unless you have some other quirky requirements) seems unnecessarily cumbersome and problematic.
Task: using Excel VBA to navigate to a website, log in and go to an input page.
On that page, sequentially enter a series of values stored in a column in Sheet1.
What I've done so far:
I create a webbrowser control and navigate to the website and stop.
Then click on a button on Sheet1 with the macros that will do the inputting, stored in a module.
What's happening:
The control comes up nicely and navigates to the intended site. (this is the userform code)
Click on the button and it gets the userid and password from the spreadsheet, inputs them, clicks on the login button and all is well.
However, the next statement is:
Set inputfield = WebBrowser.objWebBrowser.Document.getElementById("ctl02_ctl03_ddlBus")
and inputfield comes up empty.
If I stop execution and step through it, it'll work.
I've tried Application.Wait; For x = 1 to 5000000; On Error Goto/Resume and keep trying, but nothings works.
I've also tried .NavigateComplete, .DocumentCompleted, as well as others, but I get errors saying member is not supported.
I am at my wits end - I'm just so close!! So far, I've spent more time on this that it will ever save, but now it's personal! Thanks for your help.
This is borrowed code from another site that initializes the control.
Private Sub UserForm_Initialize()
Dim a, c As Integer
With Me
.StartUpPosition = 0
.Top = 150
.Left = -700
End With
With Me.objWebBrowser
.Navigate2 "http://www.schoolbuscity.com/Mapnetweb_47/login.aspx"
.Visible = True
End With
End Sub
Private Sub GetSheets()
'this is my code
Dim inputfield As Object
Dim SendText As String
Dim NumberOfRoutes, r, errCount As Integer
errCount = 0
NumberOfRoutes = Range("NumberOfRoutes")
ReDim RouteNumbers(NumberOfRoutes) As String
For r = 1 To NumberOfRoutes
RouteNumbers(r) = Cells(r, 1).Value
Next r
' Sheets("Sheet1").Select
Range(Cells(5, 2), Cells(6, 2)).ClearContents ' this indicates success for the chosen cells
SendText = Range("userid").Value
Set inputfield = WebBrowser.objWebBrowser.Document.getElementById("Login1_UserName")
inputfield.Value = SendText
SendText = Range("password").Value
Set inputfield = WebBrowser.objWebBrowser.Document.getElementById("Login1_Password")
inputfield.Value = SendText
Set inputfield = WebBrowser.objWebBrowser.Document.getElementById("Login1_Login")
Application.Wait (Now + TimeValue("0:00:01"))
inputfield.Click
Application.Wait (Now + TimeValue("0:00:01")) ' I've tried waiting for up to 10 seconds
Set inputfield = Nothing
On Error GoTo TryAgain
For r = 5 To 6 'NumberOfRoutes ' just want to use 2 loops for testing
' this is where is fails, I believe, because the page is not initialized
' but if waiting is not the answer, then what is?
Set inputfield = WebBrowser.objWebBrowser.Document.getElementById("ctl02_ctl03_ddlBus")
inputfield.Value = RouteNumbers(r)
Set inputfield = WebBrowser.objWebBrowser.Document.getElementById("ctl02_ctl03_btnGo")
inputfield.Click
Application.Wait (Now + TimeValue("0:00:01"))
Cells(r, 2).Value = "Sent"
' WebBrowser.objWebBrowser.Document.Print
WebBrowser.objWebBrowser.GoBack
Next r
GoTo EndIt
TryAgain:
Set inputfield = Nothing
Set inputfield = WebBrowser.objWebBrowser.Document.getElementById("ctl02_ctl03_ddlBus")
errCount = errCount + 1
If errCount > 5 Then GoTo EndIt
Resume
EndIt:
If errCount > 0 Then
MsgBox "errCount= " + CStr(errCount)
Else
MsgBox "Did it"
End If
End Sub
This is how to waitbin vbscript.
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = 0
'must navigate to a local file to avoid security prompts
ie.Navigate2 "C:\Users\User\Desktop\Filter.html"
Do
wscript.sleep 100
Loop until ie.document.readystate = "complete"
examples in VBA:
Private Sub UserForm_Initialize()
Set ie = Me.WebBrowser1
ie.Navigate2 "about:blank"
Do Until ie.ReadyState = READYSTATE_COMPLETE
DoEvents
Loop
Set ie = Nothing
End Sub
Private Sub Conectar_Click()
Dim ie As Object
Set ie = Me.WebBrowser1
ie.Navigate2 "http://www.mytest.com"
Do Until ie.ReadyState = READYSTATE_COMPLETE
DoEvents
Loop
'different alternatives
'Dim inputfield As Object
'Set inputfield = ie.Document.getElementById("Login_tbLogin")
'inputfield.Value = "mylogin"
'Set inputfield = Nothing
'ie.Document.getElementById("Login_tbLogin").Value = "mylogin"
'ie.Document.All("Login_tbLogin").Focus
'ie.Document.All("Login_tbLogin").Value = "mylogin"
ie.Document.All.Item("Login_tbLogin").Value = "mylogin"
Set ie = Nothing
End Sub