Iterating through collections - excel

I have a collection that I'm attempting to iterate through, which I am able to do no problem. What I would like to achieve is seeing the next object in the collection, but I am unable to find anything on this.
I've tried to look ahead using a (+ 1) in the if statement, but this doesn't seem to work.
For each a in CollBlank
if CollBlank(a + 1) <> "some value" then
'do code
end if
Next
Ideally, I'd like to be able to look ahead.
Access-vba & excel-vba are tagged since collections are used in both access and excel, I'm personally using it in Access right now, but most tutorials are through Excel.

Rather than using for each, use a for loop with an index variable, for example:
Dim i As Integer
For i = 0 to CollBlank.Count - 2
If CollBlank(i + 1) <> "some value" Then
' Do stuff
End If
Next i

Related

Performing same operation on multiple named ranges

I have a bunch of named ranges within a sheet that must get cleared every day. Currently I have it set up within VBA like this:
Range("CustomList1").ClearContents
Range("CustomList2").ClearContents
Range("CustomList3").ClearContents
Range("CustomList4").ClearContents
Range("CustomList5").ClearContents
(+15 more)
Not really a big deal but I feel like there must be a better way of going about it. That being said after doing some searching I didn't really see anything about looping through multiple named ranges. Any ideas/thoughts on this?
Dim i As Long
For i = 1 to 20
Range("CustomList" & i).ClearContents
Next
... something like that.
If you had some sort of naming convention for named ranges that you want to clear, you could do something like this which means you don't ever need to update your code ...
Dim objName As Name
For Each objName In ThisWorkbook.Names
If InStr(1, objName.Name, "NamedRange", vbTextCompare) = 1 Then
With objName.RefersToRange
.Worksheet.Range(.Address).ClearContents
End With
End If
Next
Skin's solution will work if the name is consistent, but if not, you could always create an array with all the range names.
Something Like
RngArray = Array("CustomList1","CustomList2","CustomList3, etc.")
For i = 0 to 19
Range(RngArray(i)).ClearContents
Next
A Union may be more typing than a loop but it completes the operation in a single statement.
Union(Range("CustomList1"), Range("CustomList2"), Range("CustomList3"), _
Range("CustomList4"), Range("CustomList5"), Range("CustomList6"), _
Range("CustomList7"), Range("CustomList8"), Range("CustomList9"), _
Range("CustomList10"), Range("CustomList11"), Range("CustomList12"), _
Range("CustomList13"), Range("CustomList14"), Range("CustomList15"), _
Range("CustomList16"), Range("CustomList17"), Range("CustomList18"), _
Range("CustomList19"), Range("CustomList20")).ClearContents
This method would likely be better suited to named ranges with abstract or dissimilar naming conventions.
I would do this slightly differently.
I would store the names under one name in the Formula==>Names Manager as shown below.
And then I will only use the below every where. No need for several lines of code everytime you want to clear the range.
Range("MyCustomList").ClearContents

Limit text to allowed characters only - (not by enumerating the wrong characters) | VBA

I would like to limit certain textboxes to accept only [A-Za-z]
I hope, a counterpart to Like exists.
With Like I would have to make a long list of not allowed characters to be able to filter.
Not MyString like [?;!°%/=....]
I can think of a solution in the form of:
For Counter = 1 To Len(MyString)
if Mid(MyString, Counter, 1) Like "*[a-z]*" = false then
MsgBox "String contains bad characters"
exit sub
end if
next
... but is there a more sophisticated 1liner solution ?
Until then, I have created a function to make it "Oneliner":
Function isPureString(myText As String) As Boolean
Dim i As Integer
isPureString = True
For i = 1 To Len(myText)
If Mid(myText, i, 1) Like "*[a-zA-Z_íéáűúőöüóÓÜÖÚŐŰÁÉÍ]*" = False Then
isPureString = False
End If
Next
End Function
If i add 1 more parameter, its also possible to define the allowed characters upon calling the function.
Ok, it seems my question was a bit of a duplicate, even though that did not pop in my search results.
So credits for #QHarr for posting the link.
The solution I can forge from that idea for my "oneliner" is:
If myText Like WorksheetFunction.Rept("[a-zA-Z]", Len(myText))=false then 'do something.
Using .rept is inspiringly clever and elegant in my oppinion.
So what is does: Multiplies the search criteria for each charater instead of looping through the characters.
EDIT:
In an overaboundance of nice and elegant solutions, the most recent leader is:
If not myText Like "*[!A-Za-z]*" then '... do something
Statistics update:
I have tested the last 3 solutions' performance:
I have pasted # in the below text strin at the beginning, at the end or nowhere.
The criteria were: "*[a-zA-Z \S.,]*"
For 100000 repetitions
text = "This will be a very Long text, with one unwanted in the middle, to be able to test the difference in performance of the approaches."
1.) Using the [!...] -> 30ms with error, 80ms if no error
2.) Using .Rept -> around 1800ms for all cases
3.) Using characterLoop+Mid -> around 3000ms if no error / 40-80ms ms if early error

Excel VBA On Error error

I am rather new at programming, and while learning Python also started experimenting with Excel VBA. I have an issue with the last one.
I have some large Excel sheets and tried to validate that data in specific columns matches data on another sheet in certain columns as they will be supposed to relate to each other by these values (and will be connected by a third value). To make this a bit more difficult, both of these columns may contain more than one value separated by "|". So, I have split these values in a list and I try to iterate through them to make sure all these values are set correctly, the connection will work fine.
All is fine as long as all is fine :) I have however an issue where there are two values in one of those columns and only one in the other. I would like this discrepancy to be noted on a sheet and then proceed to the next item.
The way that seemed to be applicable for me is to use "On Error GoTo ErrHandler", then note error on another sheet, and then user Resume to proceed.
Here is what I came up with:
For h = 0 To UBound(Split1())
For j = 1 To GetMaxRow("SpecificSheet", A)
On Error GoTo ErrHandler:
If Sheets("SpecificSheet").Cells(j, 1).Value = Split1(h) And Sheets("SpecificSheet").Cells(j, 2).Value = Split2(h) Then
DependencyOk = DependencyOk + 1
End If
Next j
Next h
ErrProceed:
Also ErrHandler is:
ErrHandler:
Sheets("Issues").Cells(x, 1) = "IssueDescription"
GoTo ErrProceed
It stops at line 2 with Subscript out of range for Split2(h) rather than moving on to ErrHandler and then ErrProceed. I have the feeling this must be something very obvious but I am just unable to get this working, and I am not able to find other way (like a try/except) in Excel VBA.
UPDATE:
Trying to clarify things a bit. The root of the issue is, that the Split2 list is shorter than Split1 - which is an issue with the input data and I'd like to capture this. I get the Split values from cells, where the values are separated by "|" characters:
CellValue = Sheets("SomeSheet").Cells(RowNumber, ColumNumber)
CellValueSplit() = Split(CellValue, "|")
And then iterate as:
For h = 0 To UBound(Split1())
So as Split1 moves on to the for example 3rd value, Split2 throws error and script stops. The best I was able to do so far was, that I let it proceed with the loop, but as this is a rather large sheet, it will fill the same error report ca. 200k times in this case, which I'd like to avoid. So I'd prefer it to proceed from after this loop once it hits out of range error, and proceed examining the next value.
Thank you for your help so far and in advance!
You have an issue with your syntax. The proper Error statement syntax is:
On Error GoTo <string>
On Error Resume Next
On Error GoTo 0
When using On Error GoTo <string> there is no ":" at the end. The ":" doesn't come into play until you create the target location. Example:
On Error GoTo Here
'// ---- Do something ---- //
Here:
'// ---- Handle the error ---- //
If you use On Error Resume Next, then you're telling the machine to ignore errors and proceed on to the next line of code.
When you useOn Error Return To 0, VBA will reset its error handling back to default. It's a good habit when using On Error Resume Next to insert On Error Return To 0 as soon as you no longer need it. On Error Resume Next has a real potential to break your code and make it behave strangely. Not to mention debugging can be a real nightmare. Check out the VBA manual from Microsoft for a more detailed explanation.
Finally, if your question is answered, you should mark it as answered.
vba-excelvbaexcel
The short and quick version is that VBA Error Handling Routine's only handle errors in the actual code execution, they do not fire when conditions expressed by the code are not met.
In your case, you do not need any error handling at all. In most cases it is actually best to avoid On Error GoTo .... There are cases where it's inevitable, but they are rare.
Try this IF THEN ELSE block:
If Sheets("SpecificSheet").Cells(j, 1).Value = Split1(h) And Sheets("SpecificSheet").Cells(j, 2).Value = Split2(h) Then
DependencyOk = DependencyOk + 1
Else
Sheets("Issues").Cells(x, 1) = "IssueDescription"
End If
Actually I have just found the issue. It was caused by a ":" left after an If statement a few rows earlier. I still don't really understand what it did, but I suggest not to reproduce it :)

VBScript - Either getting object required or type mismatch errors

I have scoured the web and this site looking for an answer on this, so I would really appreciate some help.
I'm creating a VBScript to do some modifications to a user-specified Excel spreadsheet. I have the first part of my script working fine, but the second part is driving me nuts. I need it to search the first column for a value and, if found, delete the row. Right now I'm not worrying about the deletion statement--I'm doing testing by seeing if I can get the For Each statement to run properly as well as the If Then statement. Here's the specific block of code:
For Each cell in objSheet.Columns("A:A").Cells
Set cell = objSheet.Columns("A:A").Cells
If cell.Value = "60802400040000" then
cell.font.bold = True
End If
Next
I have tried many variations of this and cannot find the right combination. Initially I was getting an "Object Required" messages, and after reading a number of posts, found that I needed to put in a Set statement for cell, which I did. Now I am getting a Mismatch Type error message.
The funny thing is, before I put in the Set statement, the code would execute, but it would throw the Object Required error when I closed the spreadsheet. After adding it, the error for the Type Mismatch pops up immediately.
Most examples I keep finding on the web are for VBA, and I try to modify them for VBS, which I don't know very well. Any assistance anyone can give me will be greatly appreciated.
You are redefining cell, cell is defined automatically in the For Each statement.
Delete this line
Set cell = objSheet.Columns("A:A").Cells
This is an example from Help, unfortunately Help doesn't have any examples that uses For Each, only For x = n to n and other means. For Each is the right thing to do.
Set r = Range("myRange")
For n = 1 To r.Rows.Count
If r.Cells(n, 1) = r.Cells(n + 1, 1) Then
MsgBox "Duplicate data in " & r.Cells(n + 1, 1).Address
End If
Next n
For vba to vbs, you have to create the object and use, as some objects are automatically available in VBA (like app object) - Set exceldoc = CreateObject("c:\blah\blah.xls) then to use Set r = exceldoc.worksheets(0).range("MyRange").
Also you have to use constant values not names as vbscript can't look them up.

Using .Find to look in another worksheet

I have aset of account names in one workbook (the active one), and I need to use the .Find function to look for their ocurrences in another workbook/sheet. I don't think I'm getting the right Object handle for the other workbook/sheet, but nothing I try is working.
For Count = 1 to 10
accName = Cells(Count, 1).Value
AccRow(Count) = OBJECTHANDLE.Find(accName).Row
Next Count
Any help?
Never mind, I found the answer with perserverence (it's so rare at the end of the day). Needs to have the Object defined up to .Range, so:
Workbooks("WORKBOOK").Sheets("SHEET").Range("RANGE")
I hate VBA.

Resources