So I have a loop that exports data from a website. However, for each case, it starts a new session and closes. Is there a method to navigate and download for all the cases in just one IE11 session and then closing out? Below is the code that I have right now:
Public Sub Get_File()
Dim sFiletype As String 'Fund type reference
Dim sFilename As String 'File name (fund type + date of download), if "" then default
Dim sFolder As String 'Folder name (fund type), if "" then default
Dim bReplace As Boolean 'To replace the existing file or not
Dim sURL As String 'The URL to the location to extract information
Dim Cell, Rng As Range
Dim Sheet As Worksheet
'Initialize variables
Set Rng = Range("I2:I15")
Set Sheet = ActiveWorkbook.Sheets("Macro_Button")
For Each Cell In Rng
If Cell <> "" Then
sFiletype = Cell.Value
sFilename = sFiletype & "_" & Format(Date, "mmddyyyy")
sFolder = Application.WorksheetFunction.VLookup(Cell.Value, Sheet.Range("I2:J15"), 2, False)
bReplace = True
sURL = "www.preqin.com"
'Download using the desired approach, XMLHTTP / IE
If Application.WorksheetFunction.VLookup(Cell.Value, Sheet.Range("I2:W15"), 15, False) = 1 Then
Call Download_Use_IE(sURL, sFilename, sFolder, bReplace)
Else
Call Download_NoLogin_Use_IE(sURL, sFilename, sFolder, bReplace)
End If
Else
Exit Sub
End If
Next
End Sub
Private Sub Download_Use_IE(ByRef sURL As String, _
Optional ByRef sFilename As String = "", _
Optional ByRef sFolder As String = "", _
Optional ByRef bReplace As Boolean = True)
Dim oBrowser As InternetExplorer
Dim hDoc As HTMLDocument
Dim objInputs As Object
Dim ele As Object
On Error GoTo ErrorHandler
'Create IE object
Set oBrowser = New InternetExplorer
oBrowser.Visible = True
'Navigate to URL
Call oBrowser.navigate(sURL)
While oBrowser.Busy Or oBrowser.readyState <> 4: DoEvents: Wend
'Skips log in step if already signed into website
On Error GoTo LoggedIn
'Enter username
oBrowser.document.getElementById("ctl00_ctl00_cphSiteHeader_ucLoginForm_user_email").Value = "XXX"
oBrowser.document.getElementById("ctl00_ctl00_cphSiteHeader_ucLoginForm_user_password").Value = "XXX"
'Submit the sign in
oBrowser.document.getElementById("ctl00_ctl00_cphSiteHeader_ucLoginForm_btnLogin").Click
'Wait for website to load
While oBrowser.Busy Or oBrowser.readyState <> 4: DoEvents: Wend
LoggedIn:
'All PE
oBrowser.navigate Range("H3").Value
'Wait for website to load
While oBrowser.Busy Or oBrowser.readyState <> 4: DoEvents: Wend
'Set the htmldocument
Set hDoc = oBrowser.document
'Loop and click the download file button
Set objInputs = oBrowser.document.getElementsbyTagName("input")
For Each ele In objInputs
If ele.Title Like "Download Data to Excel" Then
ele.Click
End If
Next
'Wait for dialogue box to load
While oBrowser.Busy Or oBrowser.readyState > 3: DoEvents: Wend
Application.Wait (Now + TimeValue("0:00:02"))
'IE 9+ requires to confirm save
Call Download(oBrowser, sFilename, sFolder, bReplace)
'Close IE
oBrowser.Quit
Exit Sub
ErrorHandler:
'Resume
Debug.Print "Sub Download_Use_IE() " & Err & ": " & Error(Err)
End Sub
Modify your download_IE procedure to use a Browser that is passed to it:
Private Sub Download_Use_IE(oBrowser As InternetExplorer, _
ByRef sURL As String, _
Optional ByRef sFilename As String = "", _
Optional ByRef sFolder As String = "", _
Optional ByRef bReplace As Boolean = True)
Dim hDoc As HTMLDocument
Dim objInputs As Object
Dim ele As Object
On Error GoTo ErrorHandler
'Create IE object
oBrowser.Visible = True
'Navigate to URL
Call oBrowser.navigate(sURL)
......rest of code
Call Download(oBrowser, sFilename, sFolder, bReplace)
'Do not Close IE
Exit Sub
ErrorHandler:
'Resume
Debug.Print "Sub Download_Use_IE() " & Err & ": " & Error(Err)
End Sub
Then modify your procedure to pass this object:
Public Sub Get_File()
'declare all variables plus:
Dim oBrowser As InternetExplorer
Set oBrowser = New InternetExplorer
.....put additional code here.....
If Application.WorksheetFunction.VLookup(Cell.Value, Sheet.Range("I2:W15"), 15, False) = 1 Then
Call Download_Use_IE(oBrowser, sURL, sFilename, sFolder, bReplace)
Else
Call Download_NoLogin_Use_IE(oBrowser, sURL, sFilename, sFolder, bReplace)
End If
Else
Exit Sub
End If
Next
'Close IE
oBrowser.Quit
End Sub
You will need to do the same thing for the other procedure.
Related
Im newbiee in VBA, so i need a little help.
My goal is make an Outlook rule, but i have a problem:
I want to save one excel (xlsx) file from my Outlook Inbox to my PC. But only the file which contains (in spreadsheet) a string. But it saves (or not saving anything) the last excel file.. (not checking for MYSTRING)
Using this code:
Option Explicit
Sub CheckAttachments(olItem As MailItem)
Const strPath As String = "C:\Users\PC2\Documents\Temp_attachs\"
Const strFindText As String = "Completed"
Dim strFilename As String
Dim olAttach As Attachment
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
Dim bXStarted As Boolean
Dim bFound As Boolean
If olItem.Attachments.Count > 0 Then
For Each olAttach In olItem.Attachments
If Right(LCase(olAttach.FileName), 4) = "xlsx" Then
strFilename = strPath & Format(olItem.ReceivedTime, "yyyymmdd-HHMMSS") & _
Chr(32) & olAttach.FileName
olAttach.SaveAsFile strFilename
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
Application.StatusBar = "Please wait while Excel source is opened ... "
Set xlApp = CreateObject("Excel.Application")
bXStarted = True
End If
On Error GoTo 0
'Open the workbook to read the data
Set xlWB = xlApp.Workbooks.Open(strFilename)
Set xlSheet = xlWB.Sheets("Sheet1")
If FindValue(strFindText, xlSheet) Then
MsgBox "Value found in " & strFilename
bFound = True
End If
xlWB.Close 0
If bXStarted Then xlApp.Quit
If Not bFound Then Kill strFilename
Exit For
End If
Next olAttach
End If
End Sub
Function FindValue(FindString As String, iSheet As Object) As Boolean
Dim Rng As Object
If Trim(FindString) <> "" Then
With iSheet.Range("A:J")
Set Rng = .Find(What:=FindString, _
After:=.Cells(.Cells.Count), _
LookIn:=-4163, _
LookAt:=1, _
SearchOrder:=1, _
SearchDirection:=1, _
MatchCase:=False)
If Not Rng Is Nothing Then
FindValue = True
Else
FindValue = False
End If
End With
End If
End Function
Sub Test()
Dim olMsg As MailItem
On Error Resume Next
Set olMsg = ActiveExplorer.Selection.Item(1)
CheckAttachments olMsg
End Sub
I think I found your Problem:
You have used Exit For in your For Loop only. So only after scanning 1st file, loop is exited.
You need to remove the Exit For and then your code will work smoothly.
Option Explicit
Sub CheckAttachments(olItem As MailItem)
Const strPath As String = "C:\Users\PC2\Documents\Temp_attachs\"
Const strFindText As String = "Completed"
Dim strFilename As String
Dim olAttach As Attachment
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
Dim bXStarted As Boolean
Dim bFound As Boolean
If olItem.Attachments.Count > 0 Then
For Each olAttach In olItem.Attachments
If Right(LCase(olAttach.FileName), 4) = "xlsx" Then
strFilename = strPath & Format(olItem.ReceivedTime, "yyyymmdd-HHMMSS") & _
Chr(32) & olAttach.FileName
olAttach.SaveAsFile strFilename
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
Application.StatusBar = "Please wait while Excel source is opened ... "
Set xlApp = CreateObject("Excel.Application")
bXStarted = True
End If
On Error GoTo 0
'Open the workbook to read the data
Set xlWB = xlApp.Workbooks.Open(strFilename)
Set xlSheet = xlWB.Sheets("Sheet1")
If FindValue(strFindText, xlSheet) Then
MsgBox "Value found in " & strFilename
bFound = True
End If
xlWB.Close 0
If bXStarted Then xlApp.Quit
If Not bFound Then Kill strFilename
End If
Next olAttach
End If
End Sub
Function FindValue(FindString As String, iSheet As Object) As Boolean
Dim Rng As Object
If Trim(FindString) <> "" Then
With iSheet.Range("A:J")
Set Rng = .Find(What:=FindString, _
After:=.Cells(.Cells.Count), _
LookIn:=-4163, _
LookAt:=1, _
SearchOrder:=1, _
SearchDirection:=1, _
MatchCase:=False)
If Not Rng Is Nothing Then
FindValue = True
Else
FindValue = False
End If
End With
End If
End Function
Sub Test()
Dim olMsg As MailItem
On Error Resume Next
Set olMsg = ActiveExplorer.Selection.Item(1)
CheckAttachments olMsg
End Sub
I have below code which prints text from a column but open a text file many times instead of once. Please let me know what is the wrong.
When I run sub in Visual Basic debug mode, it open text file only once. But I am calling this macro after another macro and that time it is opening (same) text file many times.
Sub createdevtest()
Dim filename As String, lineText As String
Dim data As Range
Dim myrng As Range, i, j
' filename = ThisWorkbook.Path & "\textfile-" & Format(Now, "ddmmyy-hhmmss") & ".txt"
filename = ThisWorkbook.Path & "\devtest" & ".txt"
Open filename For Output As #1
Dim LastRow As Long
'Find the last non-blank cell in column A(1)
LastRow = Cells(Rows.count, 1).End(xlUp).Row
Range("B4:B" & LastRow).Select
Set myrng = Selection
For i = 1 To myrng.Rows.count
For j = 1 To myrng.Columns.count
lineText = IIf(j = 1, "", lineText & ",") & myrng.Cells(i, j)
Next j
Print #1, lineText
Next i
Close #1
Range("B4").Select
' open devtest
'Shell "explorer.exe" & " " & ThisWorkbook.Path, vbNormalFocus
filename = Shell("Notepad.exe " & filename, vbNormalFocus)
End Sub
Thanks #Luuklag. I had tried to figure out on my own but no success. After your comment, just went thru code again and got clue.
Below is the correct code where I have called one of the macro (devtest1) which contains above text file creation macro (createdevtest). Before correction I was calling macro in function instead of Sub, so it was looping again and opening txt file many times.
' macro to select folder and list files
Sub GetFileNames_devtest()
Set Folder = Application.FileDialog(msoFileDialogFolderPicker)
If Folder.Show <> -1 Then Exit Sub
xDir = Folder.SelectedItems(1)
Call ListFilesInFolder(xDir, True)
' call devtest: corrected to call macro at right place
devtest1
End Sub
Sub ListFilesInFolder(ByVal xFolderName As String, ByVal xIsSubfolders As Boolean)
Dim xFileSystemObject As Object
Dim xFolder As Object
Dim xSubFolder As Object
Dim xFile As Object
Dim rowIndex As Long
Set xFileSystemObject = CreateObject("Scripting.FileSystemObject")
Set xFolder = xFileSystemObject.GetFolder(xFolderName)
rowIndex = Application.ActiveSheet.Range("A65536").End(xlUp).Row + 1
For Each xFile In xFolder.Files
Application.ActiveSheet.Cells(rowIndex, 1).Formula = xFile.Name
rowIndex = rowIndex + 1
Next xFile
If xIsSubfolders Then
For Each xSubFolder In xFolder.SubFolders
ListFilesInFolder xSubFolder.Path, True
Next xSubFolder
End If
Set xFile = Nothing
Set xFolder = Nothing
Set xFileSystemObject = Nothing
'' Was calling wrongly macro here
End Sub
Function GetFileOwner(ByVal xPath As String, ByVal xName As String)
Dim xFolder As Object
Dim xFolderItem As Object
Dim xShell As Object
xName = StrConv(xName, vbUnicode)
xPath = StrConv(xPath, vbUnicode)
Set xShell = CreateObject("Shell.Application")
Set xFolder = xShell.Namespace(StrConv(xPath, vbFromUnicode))
If Not xFolder Is Nothing Then
Set xFolderItem = xFolder.ParseName(StrConv(xName, vbFromUnicode))
End If
If Not xFolderItem Is Nothing Then
GetFileOwner = xFolder.GetDetailsOf(xFolderItem, 8)
Else
GetFileOwner = ""
End If
Set xShell = Nothing
Set xFolder = Nothing
Set xFolderItem = Nothing
End Function
End Function
Im seeking for help as i have a bulk of links to check if the link is broken i have tried the below macro but it works twice and after that it is no longer working i am using ms office 10 64bit i would like to add on the macro if macro
can check the image resolution for example if i paste url on column A it will highlight the broken links and on column b it will show the image resolution
Sub Audit_WorkSheet_For_Broken_Links()
If MsgBox("Is the Active Sheet a Sheet with Hyperlinks You Would Like to Check?", vbOKCancel) = vbCancel Then
Exit Sub
End If
On Error Resume Next
For Each alink In Cells.Hyperlinks
strURL = alink.Address
If Left(strURL, 4) <> "http" Then
strURL = ThisWorkbook.BuiltinDocumentProperties("Hyperlink Base") & strURL
End If
Application.StatusBar = "Testing Link: " & strURL
Set objhttp = CreateObject("MSXML2.XMLHTTP")
objhttp.Open "HEAD", strURL, False
objhttp.Send
If objhttp.statustext <> "OK" Then
alink.Parent.Interior.Color = 255
End If
Next alink
Application.StatusBar = False
On Error GoTo 0
MsgBox ("Checking Complete!" & vbCrLf & vbCrLf & "Cells With Broken or Suspect Links are Highlighted in RED.")
End Sub
Edit: I changed your macro to declare variables properly and release objects upon macro completion; this should address any potential memory issues. Please try this code and let me know if it works.
Sub Audit_WorkSheet_For_Broken_Links()
If MsgBox("Is the Active Sheet a Sheet with Hyperlinks You Would Like to Check?", vbOKCancel) = vbCancel Then
Exit Sub
End If
Dim alink As Hyperlink
Dim strURL As String
Dim objhttp As Object
On Error Resume Next
For Each alink In Cells.Hyperlinks
strURL = alink.Address
If Left(strURL, 4) <> "http" Then
strURL = ThisWorkbook.BuiltinDocumentProperties("Hyperlink Base") & strURL
End If
Application.StatusBar = "Testing Link: " & strURL
Set objhttp = CreateObject("MSXML2.XMLHTTP")
objhttp.Open "HEAD", strURL, False
objhttp.Send
If objhttp.statustext <> "OK" Then
alink.Parent.Interior.Color = 255
End If
Next alink
Application.StatusBar = False
'Release objects to prevent memory issues
Set alink = Nothing
Set objhttp = Nothing
On Error GoTo 0
MsgBox ("Checking Complete!" & vbCrLf & vbCrLf & "Cells With Broken or Suspect Links are Highlighted in RED.")
End Sub
Old Answer Below
Combining your macro (which seems to be from here) with an alternative found on excelforum yields the below code. Give it a try and let me know if it works for you.
Sub TestHLinkValidity()
Dim rRng As Range
Dim fsoFSO As Object
Dim strPath As String
Dim cCell As Range
If MsgBox("Is the Active Sheet a Sheet with Hyperlinks You Would Like to Check?", vbOKCancel) = vbCancel Then
Exit Sub
End If
Set fsoFSO = CreateObject("Scripting.FileSystemObject")
Set rRng = ActiveSheet.UsedRange.Cells
For Each cCell In rRng.Cells
If cCell.Hyperlinks.Count > 0 Then
strPath = GetHlinkAddr(cCell)
If fsoFSO.FileExists(strPath) = False Then cCell.Interior.Color = 65535
End If
Next cCell
End Sub
Function GetHlinkAddr(rngHlinkCell As Range)
GetHlinkAddr = rngHlinkCell.Hyperlinks(1).Address
End Function
Is it possible with VBA Excel to download data from a website without affecting other tasks? What I want to achieve is to be able to press a button and keep working on other tasks. Right now, when I run the code below, I can't perform other tasks or the code will break. Thanks for everyone's help/input!
Public Sub Get_File()
Dim sFiletype As String 'Fund type reference
Dim sFilename As String 'File name (fund type + date of download), if "" then default
Dim sFolder As String 'Folder name (fund type), if "" then default
Dim bReplace As Boolean 'To replace the existing file or not
Dim sURL As String 'The URL to the location to extract information
Dim pURL As String
Dim Cell, Rng As Range
Dim Sheet As Worksheet
Dim oBrowser As InternetExplorer
Set oBrowser = New InternetExplorer
Dim StartTime As Double
Dim SecondsElapsed As Double
StartTime = Timer
'Initialize variables
Set Rng = Range("I2:I15")
Set Sheet = ActiveWorkbook.Sheets("Macro_Button")
For Each Cell In Rng
If Cell <> "" Then
sFiletype = Cell.Value
sFilename = sFiletype & "_" & Format(Date, "mmddyyyy")
sFolder = Application.WorksheetFunction.VLookup(Cell.Value, Sheet.Range("I2:Z15"), 2, False)
bReplace = True
sURL = "www.preqin.com"
pURL = Application.WorksheetFunction.VLookup(Cell.Value, Sheet.Range("I2:Z15"), 16, False)
'Download using the desired approach, XMLHTTP / IE
If Application.WorksheetFunction.VLookup(Cell.Value, Sheet.Range("I2:Z15"), 15, False) = 1 Then
Call Download_Use_IE(oBrowser, sURL, pURL, sFilename, sFolder, bReplace)
Else
Call Download_NoLogin_Use_IE(oBrowser, pURL, sFilename, sFolder, bReplace)
End If
Else: GoTo Exit_Sub
End If
Next
Exit_Sub:
'Close IE
oBrowser.Quit
'Determine how many seconds code took to run
SecondsElapsed = Round(Timer - StartTime, 2)
MsgBox "This code ran successfully in " & SecondsElapsed & " seconds", vbInformation
End Sub
Private Sub Download_Use_IE(oBrowser As InternetExplorer, _
ByRef sURL As String, _
ByRef pURL As String, _
Optional ByRef sFilename As String = "", _
Optional ByRef sFolder As String = "", _
Optional ByRef bReplace As Boolean = True)
Dim hDoc As HTMLDocument
Dim objInputs As Object
Dim ele As Object
On Error GoTo ErrorHandler
oBrowser.Visible = True
'Navigate to URL
Call oBrowser.navigate(sURL)
While oBrowser.Busy Or oBrowser.readyState <> 4: DoEvents: Wend
'Skips log in step if already signed into website
On Error GoTo LoggedIn
'Enter username
oBrowser.document.getElementById("ctl00_ctl00_cphSiteHeader_ucLoginForm_user_email").Value = "XXX"
oBrowser.document.getElementById("ctl00_ctl00_cphSiteHeader_ucLoginForm_user_password").Value = "XXX"
'Submit the sign in
oBrowser.document.getElementById("ctl00_ctl00_cphSiteHeader_ucLoginForm_btnLogin").Click
'Wait for website to load
While oBrowser.Busy Or oBrowser.readyState <> 4: DoEvents: Wend
LoggedIn:
'Initial data export
oBrowser.navigate (pURL)
'Wait for website to load
While oBrowser.Busy Or oBrowser.readyState <> 4: DoEvents: Wend
'Set the htmldocument
Set hDoc = oBrowser.document
'Loop and click the download file button
Set objInputs = oBrowser.document.getElementsbyTagName("input")
For Each ele In objInputs
If ele.Title Like "Download Data to Excel" Then
ele.Click
End If
Next
'Wait for dialogue box to load
While oBrowser.Busy Or oBrowser.readyState > 3: DoEvents: Wend
Application.Wait (Now + TimeValue("0:00:02"))
'IE 9+ requires to confirm save
Call Download(oBrowser, sFilename, sFolder, bReplace)
Exit Sub
ErrorHandler:
'Resume
Debug.Print "Sub Download_Use_IE() " & Err & ": " & Error(Err)
End Sub
Try the
DoEvents
As far i know, is not easy to work with background process and excel.
Cheers.
You cannot work on the Workbook that is running the macro. You can open another instance of Excel, or a read only copy of the workbook running the macro if you would like to work within Excel while the macro is running. This question has been asked and answered before on here
It is difficult to determine from your question whether you are talking about "other tasks" as in within Excel or just on your computer in general. My above paragraph answers whether you can do tasks within Excel while the macro is running.
My code opens a page and starts to complete it. It then clicks on a button which results in a pop-up screen that needs to be completed. However, I'm not sure how to make my code access that pop up screen. Any help would be appreciated!
Here is my code:
Sub Van()
Dim IE As Object
Set IE = CreateObject("InternetExplorer.Application")
IE.navigate ("website")
IE.Visible = True
Do
DoEvents
Loop Until IE.readystate = 4
Set d = IE.document
'Code clicks on buttons and dropdowns
Application.Wait (Now + TimeValue("00:00:03"))
d.GetElementbyid("caravanMake").Value = "JAY"
End Sub
This worked for me to set the value of the first drop-down in the pop-up:
'...
Application.Wait (Now + TimeValue("00:00:03"))
Set IE2 = GetIE("https://secure.apia.com.au/NASApp/apia/CRQuoteServlet?" & _
"pageAction=openModelSelectionWindow¤tSequenceNumber=")
IE2.document.getElementsByTagName("select")(0).Value = "JAY"
'etc
Function to find an open window with a given URL:
'Find an IE window with a matching URL
'Assumes no frames.
Function GetIE(sAddress As String) As Object
Dim objShell As Object, objShellWindows As Object, o As Object
Dim retVal As Object, sURL As String
Set retVal = Nothing
Set objShell = CreateObject("Shell.Application")
Set objShellWindows = objShell.Windows
'see if IE is already open
For Each o In objShellWindows
sURL = ""
On Error Resume Next
sURL = o.LocationURL
On Error GoTo 0
If sURL <> "" Then
'Debug.Print sURL
If sURL = sAddress Then
Set retVal = o
Exit For
End If
End If
Next o
Set GetIE = retVal
End Function