Loop through line of code and change integer for getElementsByClassName - html

Previously posted on the MrExcel forum
www.mrexcel.com/board/threads/change-integer-in-code-line-for-htmldoc-getelementsbyclassname.1146814/
My original line of code was
Set DogRows1 = HTMLDoc.getElementsByClassName("rpb-greyhound rpb-greyhound-1 hover-opacity"
It works perfectly for the integer 1. However, I require to increment this by 1 and change to 2, 3, 4, 5 and 6 for other webpages, as below.
Set DogRows1 = HTMLDoc.getElementsByClassName("rpb-greyhound rpb-greyhound-6 hover-opacity"
I tried declaring some variables and adding a For Next Loop, however it will not loop through. What am I doing wrong? Have I put the For Next Loops in the wrong place?
Dim StartRaceNumber As Integer
Dim LastRaceNumber As Integer
XMLReq.Open "GET", DogPageURL, False
XMLReq.send
If XMLReq.Status <> 200 Then
MsgBox "Problem" & vbNewLine & XMLReq.Status & " - " & XMLReq.statusText
Exit Sub
End If
HTMLDoc.body.innerhtml = XMLReq.responseText
Set XMLReq = Nothing
LastRaceNumber = 6
For StartRaceNumber = 1 To LastRaceNumber
Set DogRows1 = HTMLDoc.getElementsByClassName("rpb-greyhound rpb-greyhound-" & StartRaceNumber & " hover-opacity")
For Each DogRow1 In DogRows1
Set DogNameLink1 = DogRow1.getElementsByTagName("a")(0)
NextHref = DogRow1.getAttribute("href")
NextURL = DogURL & Mid(NextHref, InStr(NextHref, ":") + 28)
Debug.Print DogRow1.innerText, NextURL
Next DogRow1
Next StartRaceNumber

Sure SIM
The scraping order is as follows:
Get Greyhound URL racecards
Greyhound Races
Get Greyhound URL Dog information
List of Greyhounds in the race
Get Greyhound Form details, this is an example for Greyhound#1
Form of Each Greyhound #1
Then loop to the next race and repeat.
As I said, from the code I can scrape only the form for greyhound#1 details for each race. I need to get the other dogs too if you can help?
These are my modules, hopefully they have imported correctly >
Option Explicit
Const DogURL As String = "https://www.timeform.com/greyhound-racing/racecards"
Sub ListDogRace()
Dim XMLReq As New MSXML2.XMLHTTP60
Dim HTMLDoc As New MSHTML.HTMLDocument
Dim TFRaceList As MSHTML.IHTMLElement
Dim TFRaces As MSHTML.IHTMLElementCollection
Dim TFRace As MSHTML.IHTMLElement
Dim NextHref As String
Dim NextURL As String
XMLReq.Open "GET", DogURL, False
XMLReq.send
If XMLReq.Status <> 200 Then
MsgBox "Problem" & vbNewLine & XMLReq.Status & " - " & XMLReq.statusText
Exit Sub
End If
HTMLDoc.body.innerhtml = XMLReq.responseText
Set XMLReq = Nothing
Set TFRaces = HTMLDoc.getElementsByClassName("wfr-race bg-light-gray hover-opacity")
For Each TFRace In TFRaces
NextHref = TFRace.getAttribute("href")
NextURL = DogURL & Mid(NextHref, InStr(NextHref, ":") + 28)
ListDogsOnPage TFRace.innerText, NextURL
Next TFRace
End Sub
Sub ListDogsOnPage(DogName As String, DogPageURL As String)
Dim XMLReq As New MSXML2.XMLHTTP60
Dim HTMLDoc As New MSHTML.HTMLDocument
Dim DogRow1 As MSHTML.IHTMLElement
Dim DogRows1 As MSHTML.IHTMLElementCollection
Dim DogNameLink1 As MSHTML.IHTMLElement
Dim NextHref As String
Dim NextURL As String
Dim StartRaceNumber As Integer
Dim LastRaceNumber As Integer
XMLReq.Open "GET", DogPageURL, False
XMLReq.send
If XMLReq.Status <> 200 Then
MsgBox "Problem" & vbNewLine & XMLReq.Status & " - " & XMLReq.statusText
Exit Sub
End If
HTMLDoc.body.innerhtml = XMLReq.responseText
Set XMLReq = Nothing
LastRaceNumber = 6
For StartRaceNumber = 1 To LastRaceNumber
Set DogRows1 = HTMLDoc.getElementsByClassName("rpb-greyhound rpb-greyhound-" & StartRaceNumber & " hover-opacity"
For Each DogRow1 In DogRows1
Set DogNameLink1 = DogRow1.getElementsByTagName("a")(0)
NextHref = DogRow1.getAttribute("href")
NextURL = DogURL & Mid(NextHref, InStr(NextHref, ":") + 28)
Debug.Print DogRow1.innerText, NextURL
Next DogRow1
Next StartRaceNumber
End Sub

Can I just confirm, it is only the URL on the page of each race for each greyhound I need, so I can scrape the greyhound's form.
As an example:
Nottingham 11.06
#1 BALLYBOUGH GARY
https://www.timeform.com/greyhound-racing/greyhound-form/ballybough-gary/59297
#2 SALACRES BRUISER
https://www.timeform.com/greyhound-racing/greyhound-form/salacres-bruiser/59746
#3 FOLLOW MY LEAD
https://www.timeform.com/greyhound-racing/greyhound-form/follow-my-lead/54898
#4 HONOUR SAMURAI
https://www.timeform.com/greyhound-racing/greyhound-form/honour-samurai/53100
#5 NIDDERDALEFLURRY
https://www.timeform.com/greyhound-racing/greyhound-form/nidderdaleflurry/56446
#6 SPORTY MELODY
https://www.timeform.com/greyhound-racing/greyhound-form/sporty-melody/58746
I already have a Power Query function I have developed to scrape the form data from that url page. I am just struggling to get that full list of 6x greyhound form urls (as above) for each and every race.
If that makes sense?

Related

VBA Grab only Main Table from HTML Web Scrape. not the whole page

I have made the work by using excel copy and paste, not by web scraping properly. I am interested in capturing ONLY the data from the main table, but instead, I an getting everything in my response. How do I get just the main table? I have tried to use ..." Set HTMLTables = HTMLDoc.getElementsByTagName("tbody").Item("3") "
Sub IE_DropDownSelect_and_Click()
Dim ie As New SHDocVw.InternetExplorer
Dim htmlDoc As New MSHTML.HTMLDocument
Dim HTMLTables As MSHTML.IHTMLElementCollection
Dim HTMLTable As MSHTML.IHTMLElement
Dim TableSection As MSHTML.IHTMLElement
Dim TableRow As MSHTML.IHTMLElement
Dim TableCell As MSHTML.IHTMLElement
Dim RowCount As Integer
Dim ColCount As Integer
Dim HTMLa As MSHTML.IHTMLElement 'TagName("a")
Dim HTMLas As MSHTML.IHTMLElementCollection 'TagName("as")
Dim RowText As String
Dim TimeFrame As Integer
Dim TimeFrame2 As String
Dim URL As String
TimeFrame2 = 1
URL = "https://forecast.weather.gov/MapClick.php?w0=t&w3=sfcwind&w3u=1&w4=sky&w5=pop&w6=rh&w7=rain&AheadHour=0&Submit=Submit&FcstType=digital&textField1=33.6414&textField2=-116.2591&site=all&unit=0&dd=&bw="
ie.Visible = True
ie.navigate URL
Do While ie.readyState <> READYSTATE_COMPLETE
Loop
Set htmlDoc = ie.document
TimeFrame = Worksheets("Selector").Range("B1").Value
TimeFrame2 = CStr(TimeFrame)
'htmlDoc.querySelector("[name=AheadHour] option[value='8']").Selected = True
htmlDoc.querySelector("[name=AheadHour] option[value='" & TimeFrame2 & "'").Selected = True
Application.Wait (Now + TimeValue("0:00:1"))
htmlDoc.getElementById("submit").Click
Application.Wait (Now + TimeValue("0:00:2"))
Worksheets("sheet1").Activate
ActiveSheet.Cells.NumberFormat = "General"
Set HTMLTables = htmlDoc.getElementsByTagName("table")
'Set HTMLTables = HTMLDoc.getElementsByTagName("tbody").Item("3")
For Each HTMLTable In HTMLTables
'Debug.Print HTMLTable.Id, HTMLTable.className; vbCr
For Each TableSection In HTMLTable.Children
'Debug.Print , TableSection.tagName
'For Each TableRow In TableRow.tagName("tr")
For Each TableRow In TableSection.Children
RowText = ""
'For Each TableCell In TableCell.tagName("td")
For Each TableCell In TableRow.Children
ColCount = ColCount + 1: Cells(RowCount + 1, ColCount).NumberFormat = "#": Cells(RowCount + 1, ColCount) = RowText & vbTab & TableCell.innerText
'RowText = RowText & vbTab & TableCell.innerText
Next TableCell
ColCount = 0
RowCount = RowCount + 1
Debug.Print , , RowText
Next TableRow
Next TableSection
Next HTMLTable
End Sub
The code you are showing is for all tables. Try with either of the following two pseudo class selectors which target the table specifically:
ie.document.querySelector("body > table:nth-child(6)")
or alter css to
body > table:nth-of-type(6)

Excel VBA - Error 91 problem when HTML value is nothing

Hi I recently discovered excel VBA and am using it to aid my study of German.
I have a list of German words but no meaning/part of speech, example sentences, etc.
I wrote a macro to go to website (https://dictionary.cambridge.org/dictionary/german-english/) and fetch html data.
However, for some words, the example sentences are not provided (Hence the html returning no value and the error 91).
I have referred to other posts concerning this and added If Not HTMLDoc.getElementsByClassName() Is Nothing Then statements, but no luck so far.
Could you please tell me how to write a code such that if there is no html value, the macro moves on and go to the next word? (word is set by integer corresponding to the cell number in the excel sheet)
Dim XMLReq As New MSXML2.XMLHTTP60
Dim HTMLDoc As New MSHTML.HTMLDocument
Dim i As Integer
Dim strURL As String
For i = 2 To 3493
strURL = "https://dictionary.cambridge.org/dictionary/german-english/" & Range("A" & i)
XMLReq.Open "Get", strURL, False
XMLReq.send
If XMLReq.Status <> 200 Then
MsgBox "Error."
Exit Sub
End If
HTMLDoc.body.innerHTML = XMLReq.responseText
Set XMLReq = Nothing
'Part
If IsObject(HTMLDoc.getElementsByClassName("pos dpos")) Then
Range("B" & i) = HTMLDoc.getElementsByClassName("pos dpos")(0).innerText
End If
'Meaning
If IsObject(HTMLDoc.getElementsByClassName("ddef_h")) Then
Range("C" & i) = HTMLDoc.getElementsByClassName("ddef_h")(0).innerText
End If
'ExampleGer
If Not HTMLDoc.getElementsByClassName("eg deg") Is Nothing Then
i = i + 1
Else
Range("D" & i) = HTMLDoc.getElementsByClassName("eg deg")(0).innerText
End If
'ExampleEng
If Not HTMLDoc.getElementsByClassName("trans dtrans hdb") Is Nothing Then
i = i + 1
Else
Range("E" & i) = HTMLDoc.getElementsByClassName("trans dtrans hdb")(0).innerText
End If
Next i
End Sub
Ok, I'm a German and therefore did not need any example words.
A word that delivers all 4 values: Haus (house)
A word that delivers only 2 values: Gummibaum (rubber plant)
Try the following code and please ...
NEVER! NEVER! NEVER! manipulate the counting variable of a for loop in the code block of the loop. Never use this i = i + 1 if i is the counting variable of the for loop. If you do that you run into problems in 99.9%
Sub Dictionary()
Dim XMLReq As New MSXML2.XMLHTTP60
Dim HTMLDoc As New MSHTML.HTMLDocument
Dim i As Integer
Dim strURL As String
'Use object variables for each node you want to read from the DOM tree
'In the code below, these variables are then used to check whether an object exists or not
Dim nodePart As Object
Dim nodeMeaning As Object
Dim nodeExampleGer As Object
Dim nodeExampleEng As Object
For i = 2 To 3493
strURL = "https://dictionary.cambridge.org/dictionary/german-english/" & Range("A" & i)
'strURL = "https://dictionary.cambridge.org/dictionary/german-english/haus"
XMLReq.Open "Get", strURL, False
XMLReq.send
If XMLReq.Status <> 200 Then
MsgBox "Error."
Exit Sub
End If
HTMLDoc.body.innerHTML = XMLReq.responseText
Set XMLReq = Nothing
'Part
Set nodePart = HTMLDoc.getElementsByClassName("pos dpos")(0)
If Not nodePart Is Nothing Then
Range("B" & i) = nodePart.innerText
End If
'Meaning
Set nodeMeaning = HTMLDoc.getElementsByClassName("ddef_h")(0)
If Not nodeMeaning Is Nothing Then
Range("C" & i) = nodeMeaning.innerText
End If
'ExampleGer
Set nodeExampleGer = HTMLDoc.getElementsByClassName("eg deg")(0)
If Not nodeExampleGer Is Nothing Then
Range("D" & i) = nodeExampleGer.innerText
End If
'ExampleEng
Set nodeExampleEng = HTMLDoc.getElementsByClassName("trans dtrans hdb")(0)
If Not nodeExampleEng Is Nothing Then
Range("E" & i) = nodeExampleEng.innerText
End If
Next i
End Sub

HTML Element Collection filled from Previous Webpage Rather than Redirected Webpage VBA

The code below navigates to a webpage, fills search boxes with queries, and submits to the results page. However, the final element collection in the script, tdtags, which is defined after the redirect, is pulling data from the original search page, rather than the results page. I currently have the while ie.busy loop and a timed delay in the script, neither of which works. I have also tried waiting until an element only present in the results page becomes available in the html, but this also does not work.
Dim twb As Workbook
Dim ie As Object
Set twb = ThisWorkbook
twb.Activate
Set ie = CreateObject("internetexplorer.application")
'church = Sheets("Control").Range("A2").Value
'minister = Sheets("Control").Range("A4").Value
location = "London" 'Sheets("Control").Range("A6").Value
'denomination = Sheets("Control").Range("A8").Value
With ie
.navigate "http://www.ukchurch.org/index.php"
.Visible = True
Do While .Busy Or .ReadyState <> 4
DoEvents
Loop
End With
Application.Wait (Now + TimeValue("00:00:02"))
Set intags = ie.document.getelementsbytagname("input")
For Each intag In intags
If intag.getattribute("name") = "name" Then
If church <> "" Then
intag.Value = church
End If
ElseIf intag.getattribute("name") = "minister" Then
If minister <> "" Then
intag.Value = minister
End If
ElseIf intag.getattribute("name") = "location" Then
If location <> "" Then
intag.Value = location
End If
Else
End If
Next intag
Set dropopt = ie.document.getelementsbytagname("select")
For Each dropo In dropopt
If dropo.classname = "DenominationDropDown" Then
Set opttags = dropo.getelementsbytagname("option")
For Each opt In opttags
If opt.innertext = denomination Then
opt.Selected = True
End If
Next opt
End If
Next dropo
On Error Resume Next
For Each intag In intags
If intag.getattribute("src") = "images/ukchurch/button-go.jpg" Then
intag.Click
Do While ie.Busy Or ie.ReadyState <> 4
DoEvents
Loop
Application.Wait (Now + TimeValue("00:00:03"))
Exit For
End If
Next intag
Application.Wait (Now + TimeValue("00:00:03"))
Set tdtags = ie.document.getelementsbytagname("td")
For Each td In tdtags
If td.classname = "pText" Then
Debug.Print td.innertext
Debug.Print ie.locationURL
pagecount = Right(td.innertext, InStr(td.innertext, ":"))
End If
Next td
Debug.Print pagecount
End Sub
Any diagnosis would be appreciated.
Automating IE is a pain, so avoid it.
The following function requests the results page directly.
Public Function GetSearchResult(Optional ByVal ResultPage As Integer = 0, Optional ByVal ChurchName As String = "", Optional ByVal Minister As String = "", Optional ByVal ChurchLocation As String = "", Optional ByVal Denomination As String = "") As Object
Dim Request As Object: Set Request = CreateObject("MSXML2.serverXMLHTTP")
Dim Result As Object: Set Result = CreateObject("htmlfile")
Request.Open "POST", "http://www.ukchurch.org/searchresults1.php", False
Request.setRequestHeader "content-type", "application/x-www-form-urlencoded"
Request.send IIf(ResultPage = 0, "", "page=" & ResultPage & "&") & "name=" & ChurchName & "&minister=" & Minister & "&location=" & ChurchLocation & "&denomination=" & Denomination
Result.body.innerHTML = Request.responseText
Set GetSearchResult = Result
End Function
An example which prints the contents of the td with classname pText inside the table containing the search results
Sub Main()
Dim Document As Object
Set Document = GetSearchResult(ChurchLocation:="London")
Dim ResultRows as Object
Dim ResultRow As Object
Set ResultRows = Document.getElementsByTagName("table")(8).getElementsByTagName("td")
For Each ResultRow in ResultRows
If ResultRow.Classname = "pText" Then
Debug.print ResultRow.innerText
End If
Next
End Sub
Update
You need to add a couple of References to your VBA project to make the following code work.
In the VBA Editor, Goto the Tools Menu, Click References and in the dialog that opens add a check next to the following two items: Microsoft XML, v6.0 and Microsoft HTML Object Library (
Public Function GetChurchDetails(ByVal ChurchID As String) As MSHTML.HTMLDocument
Dim Request As New MSXML2.ServerXMLHTTP60
Dim Result As New MSHTML.HTMLDocument
Request.Open "GET", "http://www.ukchurch.org/churchdetails.php?churchid=" & ChurchID, False
Request.send
Result.body.innerHTML = Request.responseText
Set GetChurchDetails = Result
End Function
Sub Main2()
Dim Document As MSHTML.HTMLDocument
Dim Church As MSHTML.HTMLDocument
Set Document = GetSearchResult(ChurchLocation:="London")
Dim ResultRows As MSHTML.IHTMLElementCollection
Dim ResultRow As MSHTML.IHTMLElement
Dim ChurchID As String
'Set ResultRows = Document.getElementsByTagName("table")(8).getElementsByTagName("td")
' all result links on searchresults1.php have a classname of resultslink which makes getting them much easier
Set ResultRows = Document.getElementsByClassName("resultslink")
For Each ResultRow In ResultRows
ChurchID = ResultRow.getAttribute("href")
ChurchID = Mid(ChurchID, InStr(1, ChurchID, "=") + 1)
Set Church = GetChurchDetails(ChurchID)
' code to read data from the page using Church as the Document
' eg: Church.getElemenetsByTagName("td").....
Next
End Sub
You only need to use the "post" mode when your submitting data, for everything else you can use "get"

VBA: Scraping exact elements from HTMLTable

Please can you help me to understand how to find tags a in Table with class name bptable?
I receive Object does not support this method and I don't know how to solve this problem.
Sub ListVideosOnPage(VidCatName As String, VidCatURL As String)
Dim XMLReq As New MSXML2.XMLHTTP60
Dim HTMLDoc As New MSHTML.HTMLDocument
Dim VidRow As MSHTML.IHTMLElement
Dim VidInnerRow As MSHTML.IHTMLElement
Dim VidRows As MSHTML.IHTMLElementCollection
Dim VidInnerRows As MSHTML.IHTMLElementCollection
Dim VidInnerCatID As Integer
XMLReq.Open "GET", VidCatURL, False
XMLReq.send
If XMLReq.Status <> 200 Then
MsgBox "Problem" & vbNewLine & XMLReq.Status & " - " & XMLReq.statusText
Exit Sub
End If
HTMLDoc.body.innerHTML = XMLReq.responseText
Set XMLReq = Nothing
Set VidRows = HTMLDoc.getElementsByClassName("bptable")
Set VidInnerRows = ***VidRows***.getElementsByTagName("a")
With VidRows
For VidInnerCatID = 2 To VidInnerRows.Length
Set VidInnerRow = VidInnerRows(VidInnerCatID)
'Debug.Print
Next VidInnerCatID
End With
End Sub
I would use css selectors as generally a faster selector method and reduces the loops so lower complexity. You loop a single nodeList.
Dim nodeList As Object, i As long
Set nodeList = HTMLDoc.querySelectorAll(".bptable a")
For i = 0 To nodeList.Length - 1
Debug.Print nodeList.item(i).innerText
Next
The . in front of bptable is a class selector; the space after is a descendant combinator, and the final a is a type selector. It says select a tag elements who parent has class bptable.
I am printing to the immediate window Ctrl + G
Instead of using .getElementsByTagName("a") on collection of elements you can either use VidRows(0) or try a for loop to get individual element in order to apply .getElementsByTagName("a") on them. I would opt for a for loop to serve the purpose. The following is one such way to get the content.
Sub ListVideosOnPage(VidCatName As String, VidCatURL As String)
Dim XMLReq As New XMLHTTP60
Dim HTMLDoc As New HTMLDocument
Dim VidInnerRows As Object
Dim R As Long
XMLReq.Open "GET", VidCatURL, False
XMLReq.send
If XMLReq.Status <> 200 Then
MsgBox "Problem" & vbNewLine & XMLReq.Status & " - " & XMLReq.statusText
Exit Sub
End If
HTMLDoc.body.innerHTML = XMLReq.responseText
Set XMLReq = Nothing
For Each VidInnerRows In HTMLDoc.getElementsByClassName("bptable")
With VidInnerRows.getElementsByTagName("a")
If .Length Then R = R + 1: Cells(R, 1) = .Item(0).innerText
End With
Next VidInnerRows
End Sub

VBA Code for Dynamic VLookup Between Two Open Spreadsheets from MS Access 2010

I've taken a different approach to a work project and I'm running into a wall. I've Google'd everything that I can think to Google and searched multiple forums before coming back to S.O. to ask for more help. I have a form in Access that let's users enter a customer/division combination, checks to make sure that there is an existing file path for that customer, then opens excel template files and saves them to the correct folder with a customer specific file name. This all seems to be working fine. Here's the part that has me completely stumped. The next part of this would be to open two of the excel files assigning, the Workbooks as variables xlWB1 and xlWB2 and the Worksheets as xlWS1 and xlWS2(Sheet1). I need to start in xlWB1.xlWS1.(cell D2) and do a VLookup on the value (item number) of that cell against the values of the cells in the range xlWB2.xlWS2.Range(D2:D1937). My hope was to count the total number of rows in each worksheet before starting the VLookup so that I could assign that value to a variable and use that variable to define the bottom of the range. I'm going to apologize in advance if the answer to this is something simple. I've never tried to perform any operations in Excel from Access using VBA, so I'm also struggling with the syntax. Please let me know if my question isn't clear or if there is any additional information that you need. I've pasted my starting code below.
UPDATED CODE IN CASE ANYONE ELSE NEEDS TO USE IT! THANK YOU ALL FOR THE HELP!!
Sub modExcel_SixMonth()
Const WB_PATH As String = "\\FMI-FS\Users\sharp-c\Desktop\TestDir\"
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Dim xlWS As Excel.Worksheet
Dim xlRng As Excel.Range
Dim rCount As Long
Dim xlWB2 As Excel.Workbook
Dim xlWS2 As Excel.Worksheet
Dim rCount2 As Long
Dim sFormula As String
Dim i As Long
Dim xlSheetName As String
Dim bolIsExcelRunning As Boolean
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
Set xlApp = CreateObject("Excel.Application")
Else
bolIsExcelRunning = True
End If
xlApp.Visible = False
Set xlWB = xlApp.Workbooks.Open(WB_PATH & "acct 900860 Kentucky RSTS.xlsx")
Set xlWS = xlWB.Sheets(1)
Set xlWB2 = xlApp.Workbooks.Open(WB_PATH & "acct 900860 six months.xlsx")
Set xlWS2 = xlWB2.Sheets(1)
xlSheetName = xlWS2.Name
' rCount: RSTS Row Count
rCount = xlWS.Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count
Debug.Print "rCount : " & rCount
' rCount2: 6 Months Row Count
rCount2 = xlWS2.Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count
Debug.Print "rCount2 : " & rCount2
xlWS.Activate
With xlWS
For i = 2 To rCount
sFormula = "=VLOOKUP(C" & i & ", '" & WB_PATH & "[" & "acct 900860 six months.xlsx" & "]" & _
xlSheetName & "'!$D$2:$D$" & rCount2 & ", 1, 0)"
Debug.Print sFormula
.Range("D" & i).Formula = sFormula
DoEvents
Next
End With
xlWB.Save
xlWB2.Close False 'Closes WB Without Saving Changes
Set xlWB2 = Nothing
Set xlWS = Nothing
xlWB.Close
Set xlWB = Nothing
If Not bolIsExcelRunning Then
xlApp.Quit
End If
Set xlApp = Nothing
End Sub
I think this is maybe closer to what you need. Only need a single instance of excel for both workbooks...
Sub modExcel_SixMonth()
Const WB_PATH As String = "C:\Documents and Settings\Chris\Desktop\TestDir\"
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Dim xlWS As Excel.Worksheet
Dim xlRng As Excel.Range
Dim rCount As Long
Dim xlWB2 As Excel.Workbook
Dim xlWS2 As Excel.Worksheet
Dim xlRng2 As Excel.Range
Dim rCount2 As Long
Dim sFormula As String
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWB = xlApp.Workbooks.Open(WB_PATH & "acct 900860 Kentucky RSTS.xlsx")
Set xlWS = xlWB.Sheets(1)
Set xlWB2 = xlApp.Workbooks.Open(WB_PATH & "acct 900860 six months.xlsx")
Set xlWS2 = xlWB2.Sheets(1)
' rCount: RSTS Row Count
rCount = xlWS.Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count - 1
Debug.Print "rCount : " & rCount
' rCount2: 6 Months Row Count
rCount2 = xlWS2.Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count - 1
Debug.Print "rCount2 : " & rCount2
sFormula = "=VLOOKUP(C2," & xlWS2.Range("D2:D1937").Address(True, True, , True) & _
",1,FALSE)"
Debug.Print sFormula
With xlWS
.Range("D2").Formula = sFormula
End With
End Sub
Have you tried using the same application object? I believe this was a comment on this question earlier.
Additionally, if this doesn't work, you could use the find method of the range object. I.e.
XLWB2.Range("Your range here").find(XLWB1.Range( _
"Cell containing value you're looking for").Value,lookat:=xlwhole)