I have a large macro that categorizes each line of a worksheet and once the array is built, it pastes into a column next to the data. I cannot figure out why the data is pasting #N/A for the majority of the lines. The code runs without error, and the categorization works up to the 30k-40k line range, then is #N/A from that point on. However, the array itself has all the correct values. So for some reason, when pasting the array into the excel range, its not working properly.
The code is very large, but its basically the last line of code. I have also attached a screenshot that shows the array has the correct values, it just won't past correctly into the sheet.
Locals showing the array values and the sheet showing #N/A after running the code
Sub categorizeData()
Dim SearchArray As Variant
Dim ClassifiedArray As Variant
Dim results As Variant
Dim LRow As Long
Dim i As Long
Dim j As Long
'Array to count data (starts with zero in every category)
'To add category, add another zero to array
ReDim results(0 To 38)
For i = LBound(results) To UBound(results)
results(i) = 0
Next i
'Instantiate variables
Dim conf As Variant
Dim negConf As Variant
Dim helpConfus As Variant
Dim mentalHealth As Variant
Dim plans As Variant
Dim enrollment As Variant
Dim technical As Variant
Dim cancel As Variant
Dim admRelated As Variant
'New Adds
Dim financeRel As Variant
Dim financialAid As Variant
Dim payments As Variant
Dim affordability As Variant
Dim events As Variant
Dim one As Variant
Dim two As Variant
Dim three As Variant
Dim four As Variant
Dim five As Variant
Dim a As Variant
Dim b As Variant
Dim c As Variant
Dim d As Variant
Dim e As Variant
'
Dim Deferral As Variant
Dim DropOut As Variant
Dim Faculty As Variant
Dim Bullying As Variant
Dim Transfers As Variant
Dim Deadlines As Variant
Dim Roommate As Variant
Dim TeamProject As Variant
Dim TimeOff As Variant
Dim JobLoss As Variant
Dim Donations As Variant
Dim grateful As Variant
Dim advRelated As Variant
Dim graduated As Variant
Dim counted As Boolean
Dim exists As Boolean
Dim received As Long
Dim existsC As Long
Dim sent As Long
Cells.Replace What:="=-#", Replacement:="", LookAt:=xlPart, SearchOrder _
:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False _
, FormulaVersion:=xlReplaceFormula2
Cells.Replace What:="=+#", Replacement:="", LookAt:=xlPart, SearchOrder _
:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False _
, FormulaVersion:=xlReplaceFormula2
LRow = Cells(Rows.Count, 5).End(xlUp).Row
SearchArray = Range("C1:E" & LRow)
ReDim ClassifiedArray(1 To LRow)
' "like" expressions to catch categories
' To add another word, add "*[insert word]*"
cancel = Array("*sto*p*", "*opt out*", "*quit*", "*remove*", "*unsubscribe*", "*cancel*", "*no more*", "*wrong*", "*don't want*", "*take me off*", "*i am not*")
admRelated = Array("*electronically*", "*sent*", "*transcripts*", "*diploma*", "*dimploma*", "*transcript*", "*apply*", "*application*", "*applied*", "*admissions*", "*financ*", "*admission*", "*deferred*", "*test*", "*reference*", "*placement*")
financeRel = Array("*funding*", "*loans*", "*expenses*", "*financ*", "* pay*", "*promissory note*", "* fee *", "* fws*", "*fafsa*", "*grant*", "*federal*", "* fa *", "* aid *", "*scholarship*", "* bill*", "*invoice*", "* owe *")
'Here are the 4 arrays. Just populate them using the keywords you want, following the format of "*[Word]*". The financial keywords are above if you want to use some of those.
financialAid = Array("*fafsa*")
payments = Array()
affordability = Array()
'Here are certain words that may pertain to certian events, so you can add to the events array when you need.
'addDrop: help|class|confus|add|drop|availab|open|full|space|close
'registration: problem|help|when|add|regis|class|full|availab|close|open|confus
'orientation: lost|confus|event|where|when|full|close|dorm
'graduation: ceremony|graduat|class of|cap|gown|speech|event
events = Array()
one = Array("1")
two = Array("2")
three = Array("3")
four = Array("4")
five = Array("5")
a = Array("a")
b = Array("b")
c = Array("c")
d = Array("d")
e = Array("e")
grateful = Array("*you're welcome*", "*thank*", "*thanks*", "*thankful*", "*thankyou*", "*thank you*", "*appreciate*", "*your help*", "*life saver*", "*perfect*")
advRelated = Array("*masters*", "*certificate*", "*dropped*", "*advice*", "*advisor*", "*advising*", "*credit*", "*appointment*", "* course*", "*class*", "*need to*", "*sick*", "*study abroad*", "*internship*", "*transfer*", "*major*", "*module*", "*modules*")
conf = Array("*good to go*", "*that's fine*", "*will do*", "*all good*", "*sounds good*", "*got it*", "*will do*", "*receipt*", "*requested*", "*done*", "*finished*", "*completed*", "*yes*", "*yeah*", "*yay*", "*yep*", "*yuh*", "*cool*", "*confirmation*", "*yup*", "*great*", "*alright*", "*awesome*", "*ok*", "*for sure*", "*totally*", "*on it*", "*do it*", "*that?s it*")
negConf = Array("*no*", "*nah*", "*nope*", "*isn?t*", "*sorry*", "*is not*", "*not*")
helpConfus = Array("*attempted*", "*help*", "*confused*", "*instructions*", "*hold*", "*figur*", "*huh*", "*is there*", "*help*", "*[?]*", "*talk*", "*are you*", "*holds*", "*what*", "*why*")
mentalHealth = Array("*discouraging*", "*discouraged*", "*feeling good*", "*sad*", "*need to talk*", "*counsel*", "*suicid*", "*death*", "*scar*", "*apprehensive*", "*worr*", "*anxious*", "*sick*")
plans = Array("*updated*", "*update*", "*defer*", "*plan*", "*why not attending*")
enrollment = Array("*class*", "*full time*", "*part time*", "*enrollment*", "*enrolled*", "*dual*", "*waitlist*", "*regist*")
technical = Array("*error*", "*firefox*", "*chrome*", "*browser*", "*portal*", "*access*", "*email*", "*log in*", "*login*", "*logging in*", "*logged in*", "*password*", "*lms*", "*system*", "*user name*", "*locked out*")
graduated = Array("*conferred*", "*graduated*", "*graduation*", "*class of*", "*retired*")
Deferral = Array("*deferral*", "*gap year*")
DropOut = Array("*quit*", "*drop out*")
Faculty = Array("*faculty*", "*teacher*", "*professor*")
Bullying = Array("*bully*", "*scared*", "*mean*")
Transfers = Array("*transfer*", "*leave*")
Deadlines = Array("*deadline*", "*due*", "*due date*")
Roommate = Array("*roommate*")
TeamProject = Array("*team project*", "*group project*")
TimeOff = Array("*take a break*", "*take a leave*", "*time off*")
JobLoss = Array("*lost job*", "*unemployed*")
Donations = Array("*donation*", "*day of giving*", "*alumni day*")
'Code to iterate through every message and classify
'To add new category, follow example of one below and change variable names
For j = LBound(SearchArray) To UBound(SearchArray)
Dim val As String
If SearchArray(j, 1) = "received" Or SearchArray(j, 1) = "a--received" Then
received = received + 1
SearchArray(j, 3) = LCase(SearchArray(j, 3))
val = SearchArray(j, 3)
'Opt Out
counted = False 'Used so one message isn't counted twice
exists = False 'Used to classify uncategorized messages
For i = 0 To UBound(cancel) 'Goes through array of "like" expressions
If val Like cancel(i) And counted = False Then
results(0) = results(0) + 1 'Updates Count
counted = True 'If found, do not let this expression count again
exists = True 'Don't count towards unclassified
ClassifiedArray(j) = "Classified" 'Ensuring it is of type received
End If
Next i
'Admissions
counted = False
For i = 0 To UBound(admRelated)
If val Like admRelated(i) And counted = False Then
results(1) = results(1) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Finance
counted = False
For i = 0 To UBound(financeRel)
If val Like financeRel(i) And counted = False Then
results(2) = results(2) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Grateful
counted = False
nopeCount = 0
If val Like "*no thank*" Then
nopeCount = nopeCount + 1
End If
For i = 0 To UBound(grateful)
If val Like grateful(i) And counted = False Then
results(3) = results(3) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
results(3) = results(3) - nopeCount
'Advising
counted = False
For i = 0 To UBound(advRelated)
If val Like advRelated(i) And counted = False Then
results(4) = results(4) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Positive Confirmation
counted = False
For i = 0 To UBound(conf)
If val Like conf(i) And counted = False Then
results(5) = results(5) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Negative Confirmation
counted = False
For i = 0 To UBound(negConf)
If val Like negConf(i) And counted = False Then
results(6) = results(6) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Help or Confusion
counted = False
For i = 0 To UBound(helpConfus)
If val Like helpConfus(i) And counted = False Then
results(7) = results(7) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Mental Health
counted = False
For i = 0 To UBound(mentalHealth)
If val Like mentalHealth(i) And counted = False Then
results(8) = results(8) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Plans
counted = False
For i = 0 To UBound(plans)
If val Like plans(i) And counted = False Then
results(9) = results(9) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Enrollment
counted = False
For i = 0 To UBound(enrollment)
If val Like enrollment(i) And counted = False Then
results(10) = results(10) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Technical
counted = False
For i = 0 To UBound(technical)
If val Like technical(i) And counted = False Then
results(11) = results(11) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Graduated
counted = False
For i = 0 To UBound(graduated)
If val Like graduated(i) And counted = False Then
results(12) = results(12) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Financial Aid
counted = False
For i = 0 To UBound(financialAid)
If val Like financialAid(i) And counted = False Then
results(13) = results(13) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Payments
counted = False
For i = 0 To UBound(payments)
If val Like payments(i) And counted = False Then
results(14) = results(14) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Affordability
For i = 0 To UBound(affordability)
If val Like affordability(i) And counted = False Then
results(15) = results(15) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Events
For i = 0 To UBound(events)
If val Like events(i) And counted = False Then
results(16) = results(16) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Deferral
For i = 0 To UBound(Deferral)
If val Like Deferral(i) And counted = False Then
results(28) = results(28) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'DropOut
For i = 0 To UBound(DropOut)
If val Like DropOut(i) And counted = False Then
results(29) = results(29) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Faculty
For i = 0 To UBound(Faculty)
If val Like Faculty(i) And counted = False Then
results(30) = results(30) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Bullying
For i = 0 To UBound(Bullying)
If val Like Bullying(i) And counted = False Then
results(31) = results(31) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Transfers
For i = 0 To UBound(Transfers)
If val Like Transfers(i) And counted = False Then
results(32) = results(32) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Deadlines
For i = 0 To UBound(Deadlines)
If val Like Deadlines(i) And counted = False Then
results(33) = results(33) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Roommate
For i = 0 To UBound(Roommate)
If val Like Roommate(i) And counted = False Then
results(34) = results(34) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'TeamProject
For i = 0 To UBound(TeamProject)
If val Like TeamProject(i) And counted = False Then
results(35) = results(35) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'TimeOff
For i = 0 To UBound(TimeOff)
If val Like TimeOff(i) And counted = False Then
results(36) = results(36) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'JobLoss
For i = 0 To UBound(JobLoss)
If val Like JobLoss(i) And counted = False Then
results(37) = results(37) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Donations
For i = 0 To UBound(Donations)
If val Like Donations(i) And counted = False Then
results(38) = results(38) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'a
For i = 0 To UBound(a)
If val Like a(i) And counted = False Then
results(17) = results(17) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'b
For i = 0 To UBound(b)
If val Like b(i) And counted = False Then
results(18) = results(18) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'c
For i = 0 To UBound(c)
If val Like c(i) And counted = False Then
results(19) = results(19) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'd
For i = 0 To UBound(d)
If val Like d(i) And counted = False Then
results(20) = results(20) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'e
For i = 0 To UBound(e)
If val Like e(i) And counted = False Then
results(21) = results(21) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'One
For i = 0 To UBound(one)
If val Like one(i) And counted = False Then
results(22) = results(22) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Two
For i = 0 To UBound(two)
If val Like two(i) And counted = False Then
results(23) = results(23) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Three
For i = 0 To UBound(three)
If val Like three(i) And counted = False Then
results(24) = results(24) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Four
For i = 0 To UBound(four)
If val Like four(i) And counted = False Then
results(25) = results(25) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'Five
For i = 0 To UBound(five)
If val Like five(i) And counted = False Then
results(26) = results(26) + 1
counted = True
exists = True
ClassifiedArray(j) = "Classified"
End If
Next i
'If you add a category above, make sure to update the number in this as well
'Checks messages that are not classified and makes them green to be easily visible
'Makes messages that are not classified to have a type of "a--received" so that they go to the top.
If exists = False Then
results(27) = results(27) + 1
' Cells(l, 5).Font.ColorIndex = 14
ClassifiedArray(j) = "Unclassified"
End If
'Cells(l, 5).Font.Bold = True
'Grays out sent messages
Else
sent = sent + 1
ClassifiedArray(j) = "Sent"
' Cells(l, 5).Font.ColorIndex = 16
End If
Next j
'Prints the results in the table to the right of all of the data
Cells(2, 19).Font.ColorIndex = 16
Cells(1, 19).Value = "Received: " + str(received)
Cells(2, 19).Value = "Sent: " + str(sent)
Cells(1, 15).Value = "Opt-out: " + CStr(results(0))
Cells(2, 15).Value = "Admissions related: " + CStr(results(1))
Cells(3, 15).Value = "Finance related: " + CStr(results(2))
Cells(4, 15).Value = "Grateful: " + CStr(results(3))
Cells(5, 15).Value = "Advising: " + CStr(results(4))
Cells(6, 15).Value = "Positive Confirmation: " + CStr(results(5))
Cells(7, 15).Value = "Negative Confirmation: " + CStr(results(6))
Cells(8, 15).Value = "Help/Confusion: " + CStr(results(7))
Cells(9, 15).Value = "Mental Health: " + CStr(results(8))
Cells(10, 15).Value = "Plans: " + CStr(results(9))
Cells(11, 15).Value = "Enrollment: " + CStr(results(10))
Cells(12, 15).Value = "Technical: " + CStr(results(11))
Cells(13, 15).Value = "Graduated: " + CStr(results(12))
Cells(14, 15).Value = "FAFSA: " + CStr(results(13))
Cells(15, 15).Value = "Payments: " + CStr(results(14))
Cells(16, 15).Value = "Affordability: " + CStr(results(15))
Cells(17, 15).Value = "Events: " + CStr(results(17))
Cells(18, 15).Value = "Deferral: " + CStr(results(28))
Cells(19, 15).Value = "DropOut: " + CStr(results(29))
Cells(20, 15).Value = "Faculty: " + CStr(results(30))
Cells(21, 15).Value = "Bullying: " + CStr(results(31))
Cells(22, 15).Value = "Transfers: " + CStr(results(32))
Cells(23, 15).Value = "Deadlines: " + CStr(results(33))
Cells(24, 15).Value = "Roommate: " + CStr(results(34))
Cells(25, 15).Value = "TeamProject: " + CStr(results(35))
Cells(26, 15).Value = "TimeOff: " + CStr(results(36))
Cells(27, 15).Value = "JobLoss: " + CStr(results(37))
Cells(28, 15).Value = "Donations: " + CStr(results(38))
Cells(1, 17).Value = "Polling Answers"
Cells(2, 17).Value = "A: " + CStr(results(17))
Cells(3, 17).Value = "B: " + CStr(results(18))
Cells(4, 17).Value = "C: " + CStr(results(19))
Cells(5, 17).Value = "D: " + CStr(results(20))
Cells(6, 17).Value = "E: " + CStr(results(21))
Cells(7, 17).Value = "One: " + CStr(results(22))
Cells(8, 17).Value = "Two: " + CStr(results(23))
Cells(9, 17).Value = "Three: " + CStr(results(24))
Cells(10, 17).Value = "Four: " + CStr(results(25))
Cells(11, 17).Value = "Five: " + CStr(results(26))
Cells(29, 15).Value = "Unclassified: " + CStr(results(27))
Cells(29, 15).Font.ColorIndex = 14
Cells(1, 13).Resize(LRow, 1) = Application.Transpose(ClassifiedArray)
MsgBox "Action completed"
End Sub
I'm new to VBA and I'm trying to scrape data from a website. I've used nested loop. When the innermost loop finishes for the first time, the next loop starts for marakez.
Actual problem is that when 'for each in schl2' loop repeats for second time, IE crashes and loop is unable to proceed. I have mentioned in code.
Here is my code
Sub ResultDownloader()
' here I define elemnts for the loop
Dim sht As Worksheet
Set sht = ThisWorkbook.Sheets("LocData")
Dim LastRow As Long
Dim i As Long
Dim imagePath As Object
LastRow = sht.Cells(sht.Rows.Count, "D").End(xlUp).Row
startrec = sht.Cells(sht.Rows.Count, "E").End(xlUp).Row
startrec = startrec + 1
Dim IE As Object
Dim Doc As HTMLDocument
' Set IE = CreateObject("InternetExplorer.Application")
Set IE = CreateObject("InternetExplorer.Application")
' here I define Object to sendkeys
Dim SHELL_OBJECT
SHELL_OBJECT = "WScript.Shell"
Set objShell = CreateObject(SHELL_OBJECT)
Record2Strt = (sht.Cells(sht.Rows.Count, "E").End(xlUp).Row) + 1
IE.Visible = True
IE.Navigate "some_url"
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now)
Loop
Dim HTMLdoc As HTMLDocument
Dim selectElement, selectElement2, selectElement3 As HTMLSelectElement
Dim evtChange As Object
Set Doc = IE.Document
Dim dist1, tehsl1, mrkz1, schl1 As Object
Dim dist2, tehsl2, mrkz2, schl2 As Variant
Dim distlen, thsllen, mrkzlen, schllen As Byte
Dim dst, tsl, mrkz, schl As Byte
Dim elt3, elt4, elt5, elt6 As Variant
Set evtChange = Doc.createEvent("HTMLEvents")
evtChange.initEvent "change", True, False
Set dist1 = Doc.querySelector("Select[name=districts]")
Set dist2 = dist1.querySelectorAll("option")
distlen = dist1.querySelectorAll("option").Length
dst = 0
For Each elt3 In dist2
distnme = elt3.innerText
If distnme <> "All Districts" Then
dist1.getElementsByTagName("option")(dst).Selected = True
Set selectElement2 = Doc.getElementsByTagName("option")(dst)
selectElement2.dispatchEvent evtChange
Application.Wait DateAdd("s", 0.5, Now)
Set tehsl1 = Doc.querySelector("Select[name=tehsil]")
Set tehsl2 = tehsl1.querySelectorAll("option")
thsllen = tehsl1.querySelectorAll("option").Length
tsl = 0
For Each elt4 In tehsl2
thslnme = elt4.innerText
If thslnme <> "All Tehsils" Then
Set tehsl1 = Doc.querySelector("Select[name=tehsil]")
tehsl1.getElementsByTagName("option")(tsl).Selected = True
Set selectElement3 = tehsl1.getElementsByTagName("option")(tsl)
selectElement3.dispatchEvent evtChange
Application.Wait DateAdd("s", 0.5, Now)
Set mrkz1 = Doc.querySelector("Select[name=markaz]")
Set mrkz2 = mrkz1.querySelectorAll("option")
mrkzlen = mrkz1.querySelectorAll("option").Length
mrkz = 0
For Each elt5 In mrkz2
mrkznm = elt5.innerText
If mrkznm <> "All Marakez" Then
Set mrkz1 = Doc.querySelector("Select[name=markaz]")
mrkz1.getElementsByTagName("option")(mrkz).Selected = True
Set selectElement4 = mrkz1.getElementsByTagName("option")(mrkz)
selectElement4.dispatchEvent evtChange
Application.Wait DateAdd("s", 0.5, Now)
Set schl1 = Doc.querySelector("Select[name=school]")
Set schl2 = schl1.querySelectorAll("option")
schllen = schl1.querySelectorAll("option").Length
schl = 0
' second loop problem
' when for each elt6 in schl2 starts IE crashes
On Error Resume Next
For Each elt6 In schl2
Application.Wait DateAdd("s", 0.5, Now)
schlnm = elt6.innerText
If schlnm <> "All Schools" Then
Set schl1 = Doc.querySelector("Select[name=school]")
schl1.getElementsByTagName("option")(schl).Selected = True
Set selectElement5 = schl1.getElementsByTagName("option")(schl)
selectElement5.dispatchEvent evtChange
sht.Range("A" & LastRow + 1).Value = LastRow
sht.Range("B" & LastRow + 1).Value = distnme
sht.Range("C" & LastRow + 1).Value = thslnme
sht.Range("D" & LastRow + 1).Value = mrkznm
sht.Range("E" & LastRow + 1).Value = schlnm
LastRow = LastRow + 1
End If 'for school
schl = schl + 1
If schllen = schl Then
GoTo new_marakez
On Error Resume Next
End If
Next 'ele6
End If 'for marakez
new_marakez:
mrkz = mrkz + 1
If mrkzlen = mrkz Then
Exit For
GoTo new_tehsil
End If
Next 'ele5
On Error Resume Next
End If 'for tehsils
new_tehsil:
tsl = tsl + 1
If thsllen = tsl Then
GoTo new_dist
End If
Next 'ele4
On Error Resume Next
End If 'for districts
new_dist:
dst = dst + 1
If distlen = dst Then
GoTo stopp
End If
Next 'ele 3
On Error Resume Next
stopp:
End Sub
There is apparently a bug when using querySelectorAll with a generic object for your elements, in your case here 'schl2.', and using a for each...next loop. I solved this by using a standard for...next loop basically limiting the for loop, in your case, schl2.Length - 1. However, this will not work unless you define schl2 as MSHTML.IHTMLDOMChildrenCollection. If you leave this as generic, the schl2.Length will be NULL. The code below shows how I got around the problem.
`'Create html object to hold IE Document
Set html = IE.Document
Debug.Print "********* GET FIELDS ******" & vbCrLf
Dim res1 As MSHTML.IHTMLDOMChildrenCollection
Set res1 = html.querySelectorAll("#HtmlOutputReportResults2_Explorer_Filters_Column option:checked")
For r = 0 To res1.Length - 1
If res1(r).innerText <> "..." Then
Debug.Print "res1.Text: " & res1(r).innerText
End If
Next
Debug.Print vbCrLf & "********* GET OPERATORS ******" & vbCrLf
Dim res2 As MSHTML.IHTMLDOMChildrenCollection
Set res2 = html.querySelectorAll("#HtmlOutputReportResults2_Explorer_Filters_Operator option:checked")
For r = 0 To res2.Length - 1
If res2(r).innerText <> "..." Then
Debug.Print "res2.Text: " & res2(r).innerText
End If
Next`
I've been doing some VBA stuff lately but i don't know what directions to take.
Someone here helped me with the copy to Word, i've lost the topic but thanks a lot!
Is there a better way to read in the BookMarks and how can i get them to link the right sheet in this line;
MyArray(i)
'needs to go in to;
wb.worksheet(Myarray(i)).range("A1:BA3000")
I've been spending way to many hours on the array part.
Private Sub ranges()
Dim NamedRange As name
Dim nm As name
Dim ws As Worksheet
Dim Lr As Long
Dim Lc As Long
Dim Rng As range
Dim Bm As name
Dim wb As Workbook
Dim Fill As range
Dim wd As Word.Application
Set wd = New Word.Application
Set wb = ThisWorkbook 'Workbooks("C:\Excel")
Set aWs = ActiveSheet
'array with names of the word bookmarks
Dim myArray(38)
myArray(0) = ("Tappunten")
myArray(1) = ("test1")
myArray(2) = ("Groslijst")
myArray(3) = ("J01_2")
myArray(4) = ("D01")
myArray(5) = ("D03")
myArray(6) = ("W01")
myArray(7) = ("W02")
myArray(8) = ("W03")
myArray(9) = ("W04")
myArray(10) = ("M01")
myArray(11) = ("M03")
myArray(12) = ("M04")
myArray(13) = ("M05")
myArray(14) = ("HJ01")
myArray(15) = ("J01")
myArray(16) = ("M02")
myArray(17) = ("J03")
myArray(18) = ("J04")
myArray(19) = ("J05")
myArray(20) = ("J06")
myArray(21) = ("J07")
myArray(22) = ("J08")
myArray(23) = ("J09")
myArray(24) = ("J10")
myArray(25) = ("J11")
myArray(26) = ("J12")
myArray(27) = ("J13")
myArray(28) = ("J14")
myArray(29) = ("J15")
myArray(30) = ("OT03")
myArray(31) = ("OT06")
myArray(32) = ("OT07")
myArray(33) = ("Checklist")
myArray(34) = ("ObjectGegevens")
myArray(35) = ("Grondstof")
myArray(36) = ("Drinkwaterinstallatie")
myArray(37) = ("WTB")
myArray(38) = ("Warmwaterleidingnet")
'array for the worksheets on the excel sheets
Dim myArray2(38)
myArray2(0) = Worksheets(1).name
myArray2(1) = Worksheets(1).name
myArray2(2) = Worksheets(42).name
myArray2(3) = Worksheets(17).name
myArray2(4) = Worksheets(2).name
myArray2(5) = Worksheets(15).name
myArray2(6) = Worksheets(22).name
myArray2(7) = Worksheets(3).name
myArray2(8) = Worksheets(28).name
myArray2(9) = Worksheets(29).name
myArray2(10) = Worksheets(4).name
myArray2(11) = Worksheets(6).name
myArray2(12) = Worksheets(29).name
myArray2(13) = Worksheets(46).name
myArray2(14) = Worksheets(7).name
myArray2(15) = Worksheets(16).name
myArray2(16) = Worksheets(5).name
myArray2(17) = Worksheets(13).name
myArray2(18) = Worksheets(12).name
myArray2(19) = Worksheets(47).name
myArray2(20) = Worksheets(9).name
myArray2(21) = Worksheets(13).name
myArray2(22) = Worksheets(14).name
myArray2(23) = Worksheets(14).name
myArray2(24) = Worksheets(32).name
myArray2(25) = Worksheets(1).name
myArray2(26) = Worksheets(1).name
myArray2(27) = Worksheets(1).name
myArray2(28) = Worksheets(1).name
myArray2(29) = Worksheets(8).name
myArray2(30) = Worksheets(19).name
myArray2(31) = Worksheets(33).name
myArray2(32) = Worksheets(18).name
myArray2(33) = Worksheets(27).name
myArray2(34) = Worksheets(25).name
myArray2(35) = Worksheets(36).name
myArray2(36) = Worksheets(26).name
myArray2(37) = Worksheets(20).name
myArray2(38) = Worksheets(38).name
i = 1
For Each nm In ThisWorkbook.Names
If nm.Visible Then
Set NamedRange = wb.Names.Item(i)
Set ws = NamedRange.RefersToRange.Parent
End If
Lr = wb.worksheet(Myarray(i)).range("A1:BA3000").Find(What:="*", _ LookIn:=xlValues, _
SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious,
SearchFormat:=False).Row
Lc = wb.worksheet(Myarray(i)).range("A1:BA3000").Find(What:="*", _ LookIn:=xlValues, _
SearchOrder:=xlByColumns, _ SearchDirection:=xlPrevious, _
SearchFormat:=False).Column
Set Rng = ws.range(ws.Cells(1, 1), ws.Cells(Lr, Lc))
With wd
.Visible = True
.WindowState = wdWindowStateMaximize
With .Documents.Add(Template:="C:\RABP sjabloon clean.dotx")
With .Bookmarks
myArray(i).range.PasteExcelTable LinkedToExcel:=False, _
WordFormatting:=True, RTF:=False
Rng.Copy ws.range(i)
End With
End With
End With
i = i + 1
Next nm
End Sub
There are 2 ways that you could populate your array:
Method 1:
myArray = Split("Tappunten test1 Groslijst ...", " ")
Method 2:
Sub LoopThroughBookmarks()
Dim oBookmark As Bookmark
Dim myArray() As String
ReDim Preserve myArray(0)
For Each oBookmark In ActiveDocument.Bookmarks
ReDim Preserve myArray(UBound(myArray) + 1)
myArray(UBound(myArray) - 1) = oBookmark.Name
Next
End Sub
The bookmarks will be entered in the order in which they occur in the document, you may want to add some validation for the bookmarks so that you don't add some by mistake.
I've no idea how to match the bookmarks to the 2nd array :-/
I've ended up using these 2 pieces of code;
Sub Copy_to_word()
Dim wdApp As New Word.Application
Dim wdDoc As Word.Document
Dim i As Long
Dim names As Range
Application.ScreenUpdating = False
Application.EnableEvents = False
'location of the word template
Const StrDocNm As String = "C:\Word template V2.0.dotx"
If Dir(StrDocNm) = "" Then Debug.Print "file missing"
If Dir(StrDocNm) = MsgBox "Template not found"
If Dir(StrDocNm) = "" Then Exit Sub
'Could probebly make it a bit neather
Set wdDoc = wdApp.Documents.Add(Template:=StrDocNm)
wdApp.Visible = True
'All the named ranges have the same name as the bookmark
With ThisWorkbook
For i = 1 To .names.Count
On Error GoTo LosseCell:
.names(i).RefersToRange.Copy
Debug.Print .names(i).Name
'When the range is copied it starts the next macro.
'if there's an error it goes tot the next name range
Call PasteBookmark(wdDoc, .names(i).Name)
LosseCell:
Next
End With
Set wdDoc = Nothing: Set wdApp = Nothing
'because it takes some time it had the events and screenupdating turned off
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
The second marcro is the part that pastes the range in to word;
Sub PasteBookmark(wdDoc As Word.Document, strBkMk As String)
Dim wdRng As Word.Range
With wdDoc
Application.ScreenUpdating = True 'not sure if this helps to be honest
Application.EnableEvents = True 'not sure if this helps to be honest
If .Bookmarks.Exists(strBkMk) Then
Set wdRng = .Bookmarks(strBkMk).Range
wdRng.Paste
.Bookmarks.Add strBkMk, wdRng
End If
End With
Set wdRng = Nothing
End Sub
Because the ranges vary in size i also have a macro that resizes the named ranges that can vary in row count;
Sub RangesAanpassen()
Dim NmdRngNames As Variant
Dim myLastRow As Long
Dim StrWsNaam As String
Dim strRangeNaam As String
Dim namRange As Name
Dim wsRange As Worksheet
Dim n As Variant
'the ranges that need to be resized are named the same as the sheets there
'on. It gave a lot of troubles because the sheets had names like "D01".
'Had to change all of them to a name that didn't look like a cell.
NmdRngNames = Array("D_03", "D_01", "J_01", "_6.4.3_Temperatuurmetingen",
"WTB", "Tappunten", "_6.4.2_Tappunten_inv", "Voorblad")
Application.ScreenUpdating = False
Application.EnableEvents = False
For Each n In NmdRngNames
strRangeNaam = n
On Error GoTo NextN: when the range is empty a "no object" error shows.
Set namRange = ActiveWorkbook.names.Item(strRangeNaam)
Set wsRange = Range(strRangeNaam).Worksheet
With wsRange
'the last cell can be anywhere in columns A to Z.
myLastRow = .Columns("A:Z").Find(What:="*", LookIn:=xlValues, _
SearchDirection:=xlPrevious, _
SearchOrder:=xlByRows).Row
End With
With namRange
.RefersTo = wsRange.Range(wsRange.Cells(1, 1), _
wsRange.Cells(myLastRow, 1))
End With
NextN:
Next
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
Thanks for the great forum!
I am trying to design a vba macro script for Mac Office 2011 that uses find in column A to find a filename previously selected by the user.
The user selects a .csv file, then macro looks through column A to find filename without .csv extension. Once found, it offsets by one column (to column B) and imports the csv information.
What I currently have is not doing the find and then select? I can't seem to figure out what I am doing wrong here.
The csv will import, but just next to the cell I had active before running macro. This is why I think the Find is not working.
Any help would be most appreciated.
Sub CSVauto()
'
' CSVauto Macro
'
' Keyboard Shortcut: Option+Cmd+x
'
' Declaring and setting variables for choosing CSV to import
Dim csvFileName As Variant
''Prompt window to choose csv file
csvFileName = Application.GetOpenFilename(FileFilter:="")
If csvFileName = False Then Exit Sub
'Setting a variable to find Experimental form name in Data Summary
Dim whatToFind As String 'Declaring that variable
If Right(csvFileName, 4) = ".csv" Then
whatToFind = Replace(csvFileName, ".csv", "")
Else
MsgBox "Selected File Not .csv)"
End If
'Looping through A column to find csvFileName without .csv extension
Set cell = Range("A:A").Find(What:=whatToFind, LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False)
If Not cell Is Nothing Then
cell.Select
End If
'Speeding macro up by making it work in background
Sheets("DataSummary").DisplayPageBreaks = False
Application.DisplayAlerts = False
Dim MyRange As Range
Set MyRange = ActiveCell.Offset(0, 1)
MyRange.Select
'xlOverwriteCells
On Error Resume Next
'Formatting for CSV and input
With MyRange.Parent.QueryTables.Add(Connection:="TEXT;" & csvFileName, Destination:=MyRange)
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = False
.TextFilePromptOnRefresh = False
.TextFilePlatform = xlMacintosh
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = True
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = True
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.Refresh BackgroundQuery:=False
.UseListObject = False
End With
'Formatting DataSummary sheet to fit "requirements" :)
Cells.Replace What:=">=", Replacement:="", LookAt:=xlPart, SearchOrder:=xlByColumns, MatchCase:=False
Cells.Replace What:="C121", Replacement:="C2", LookAt:=xlPart, _
SearchOrder:=xlByColumns, MatchCase:=False
Cells.Replace What:="P1211", Replacement:="P21", LookAt:=xlPart, _
SearchOrder:=xlByColumns, MatchCase:=False
Cells.Select
With Selection
.HorizontalAlignment = xlLeft
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
End With
With Selection
.HorizontalAlignment = xlCenter
.Orientation = 0
.AddIndent = False
.ShrinkToFit = False
End With
Range("A4").Select
' Set Do loop to stop when an empty cell is reached.
Do Until IsEmpty(ActiveCell)
' Insert your code here.
' Step down 1 row from present location.
ActiveCell.Offset(1, 0).Select
Loop
'undoing everything working in background
Sheets("DataSummary").DisplayPageBreaks = True
Application.ScreenUpdating = True
End Sub
Take a look at where you "Set cell =...." you are having it look for whatToFind.
In your if/else statement above that, you never set whatToFind in the "else" statement. You need to set whatToFind as something in the else statement, if I am reading your request correctly.
It looks to me what you are asking for is to find a file that is NOT a .csv then to perform the function of searching/offset.
Please correct me if I am wrong or please clarify.
EDIT
This code should work for you. I tried it with your code with this inserted just below the if/else statement
Dim filename As Variant
filename = Mid(whatToFind, InStrRev(whatToFind, "/") + 1)
MsgBox filename