Find a Specific Cell entry in a Column in VBA - vba

I'm working on creating a userform for reviewing an excel sheet. I need to search a specific column to see if the user has already reviewed the row. If they have, the cell will be filled with "Reviewed", if it hasn't been reviewed yet it will have "Not Reviewed" in it.
Each department has their own Column logging whether the Row has been reviewed or not. I.e. Dept1 may have reviewed the row, while Dept2 has not yet.
I've tried something like
With Sheets("ECR")
UnReviewedRow = .Range(DepartmentReviewColumn:DepartmentReviewColumn).Find(what:="Not Reviewed", after:=.Cells(DepartmentReviewColumn, 3)).Row
End With
But I'm getting an error, not quite sure where it's coming from though. The hardcoded "3" is because I know that all entries begin at row three, everything above is headers.
I've found a few different similar questions, but they all assume that the column being searched will be the same every time. My issue is that I don't want to code this for each department, I'd like to be a bit more elegant than that.

Something like this:
With Sheets("ECR")
UnReviewedRow = .Range(DepartmentReviewColumn & ":" & DepartmentReviewColumn).Find(What:="Not Reviewed", After:=.Cells(3, DepartmentReviewColumn)).Row
End With
Modifications made:
Range() now takes a properly built string argument;
Cells() now has a row number as its first argument, and a column expressed as a string as its second argument.
Note that this code will fail with Object variable or With block variable not set if the search string is not found. You can handle this situation by initializing UnReviewedRow to e.g. 0 (zero) and putting On Error Resume Next above the Find call, and On Error Resume <either 0 or your original error handler's label> below the Find call. Then, check if UnReviewedRow = 0 and act appropriately.
Always put Option Explicit at the top of modules and classes, and compile your code (Debug / Compile VBAProject). When posting, include the text of all errors encountered.

Related

Run-time error '5852' when iterating over revisions

I am easily annoyed by word tracking format changes (even in text that is newly inserted in a revision), so I am using a macro to accept all format changes, once they summed up:
Sub AcceptAllFormatChanges()
Dim xRev As Revision
Dim count As Integer
count = 0
For Each xRev In ActiveDocument.Revisions
If Not xRev Is Nothing Then
If xRev.Type = wdRevisionProperty Then
count = count + 1
xRev.Accept
End If
End If
Next xRev
MsgBox ("Accepted " & count & " format changes")
End Sub
This works fine most of the time, but on some documents, it gives me a run-time error '5852' - Requested object is not available on the "If xRev.Type" line. I am looking for a way to check the object that is yielded by ActiveDocument.Revisions without it throwing a run-time error. Checking for Nothing is not enough. The issue also occures when removing the xRev.Accept or when looping backwards through the revisions.
Update: I tracked down the issue to a Word Bug today. If the macro strikes, I am also unable to iterate through changes in the document using the Next Change button on the review panel. Additionally, if I open the revision panel, the number of revisions jumps back and forth between two numbers. This helped me track down those ghost revisions to a few insertions which included fields (references to other sections). I am able to correct those by deleting/reinserting, so at least now I know how to fix my documents to make the macro work again. Unfortunately, I cannot reproduce the bug in order to actually file a bug report.
The VBA question though remains open: Is there a way for the macro to skip those ghost revisions without throwing a run-time error?
Use the WdRevisionType enumeration instead of cryptic numbers in the code for checking the Type property. Also you may try to check for Nothing before getting the Type property value. The following code works like a charm for me:
Public Sub AcceptSelection()
Dim rev As Revision
For Each rev In Selection.Range.Revisions
rev.Accept
Next rev
End Sub
And the last resort is to replace the for each loop with a reverse for loop.

Excel VBA Match if value is null

I have a piece of code within a larger script that simply allocates a value to "i" based on a match. The idea being I want it to give the match value if the value entered is found, or 0 if not. If it's 0, I can then exit sub with a message to the user. However, any time the match finds a null value, it just kills the sub, instead of it being handled as part of the iferror I've introduced. I've tried various manners of checking (using iif(iserror) for example) but none seem to work.
Code causing the issue is below:
i = Application.WorksheetFunction.IfError(Application.WorksheetFunction.Match(username, EL.Range("A:A"), 0), 0)
i is dim as an integer
Username is dim as a string, and comes from an inputbox
EL is dim as a worksheet, and contains the correct info.
This has absolutely no issues if I introduce any name that exists, it only fails as soon as I input a name that does not work, and I'm sort of stumped as to why. I see no reason for it to fail, but feel like I'm missing something simply and in-my-face.
Use this instead. Using Application instead of WorksheetFunction enables the error to be trapped and tested.
i = Application.IfError(Application.Match(UserName, EL.Range("A:A"), 0), 0)
I would use a slightly different approach to trap an error on Application.Match function:
Dim i As Variant
i = Application.Match(UserName, EL.Range("A:A"), 0)
' if Match wasn't able to found a "match"
If IsError(i) Then i = 0

VBA Find (LookAt=xlWhole) will always return an error

I have a search function in a VBA code that searches column A. Column A is filled with acronyms and the corresponding rows in Column B are the meanings for that acronym.
I have a user form setup that the user can enter an acronym and if it is in the file, it will show a message box saying what that acronym means.
I am trying to search for an exact match of the acronym the user enters, via this line:
Range("A:A").Find(acro, LookAt = xlWhole).Select
However, when I run it, even if I copy a cell containing an acronym and paste it into the user form text box, it will act as if it could not find it and follows my On Error handle.
What did I do wrong that made it unable to find the acronym string I am looking for?
Thank you!
#nwhaught already answered and pointed out the real issue, but to add something too large for a comment:
It's best not to chain Select/Activate directly to Find():
Range("A:A").Find(acro, LookAt = xlWhole).Select
...since that requires error handling when the item is not found (and as you discovered that can mask other issues with your code)
Try something like this instead:
Dim f
Set f = Range("A:A").Find(acro, LookAt := xlWhole)
If Not f Is Nothing then
'do something with f
End If
The Is Nothing test avoids the use of error handling.
Your On Error handle is masking the true cause of the error.
Code should be Range("A:A").Find(What:=acro, LookAt:= xlWhole).Select
When debugging, it's best to disable error handling, as the whole point of handling an error is to mask its effect to the user. (which makes debugging nearly impossible)

VBA Compile error

I have very little experience with VBA and the last time I used it was years ago.
Heres my VBA:
Function MacIDGen(total, current)
If total - current = 0 Then
current -1
Else
current 1
End If
Macro1 (current)
End Function
Sub Macro1(cur)
Sheets("Donations").Cells(I2).Value = cur & "Test"
End Sub
It's its own module, no other code in with it at all.
So I have a cell which is calling MacIDGen(). It's passing MacID two other cell values. The error comes whenever it's executed, "Compile Error: Expected Sub, Function, or Property" and highlights the functions method signature.
I have no idea why its kicking this up here, I'm guessing its because I've either missed a major step or something about how you can't have a function in that context or some other such issue.
EDIT
As a little extra info, I'm creating these spreadsheets in Excel to serve as random data generation sheets to be imported into a drupal site. I've encountered a problem that cannot be resolved without the use of loops (I also can't hard code the number of iterations either), which formulas don't do.
Regarding the Compile Error, you are getting that because you forgot to use the = sign in current -1 and current 1
Like I mentioned, there are many errors but the main error is that you cannot use a UDF to write to another cell. It really doesn't matter if you break that function into functions or subs. You simply can't write to any other cell. You will get a #Value in the cell where you are using that function.
A Function is used when you want to return something. Now since you are using this as a UDF (user defined function), it should return something and to that particular cell.
If you are writing to the same cell where the function is called from then change your code to
Function MacIDGen(total, current)
If total - current = 0 Then
current = -1
Else
current = 1
End If
MacIDGen = current & "Test"
End Function
If you want to change a cell you can use a sub procedure instead of a UDF, in that case you will need a way to execute it from your spreadsheet such as a commandButton, a ribbon button or a key combination shortcut.
If so, your first line should be:
Sub MacIDGen(total, current)

VBA Excel + using match function

I'm having some kind of problem in a piece of code.
I need to find values in a excel book and then copy it to another. The thing is that i need to copy it concept by concept in the right place. The problem is that the file doesnt come every week in the same order.
So i need to find the concept and then copy the next cell that is the value of that concept.
First of all i use need to locate the correct line so i can start copying (this part is easy and its done).
Secondly, having the correct line, i need to find the concept, which in this example im going to use the "619".
After having find the location of this value i store the value in "c_audiovisual".
On Error GoTo ErrhandlerCAV
lRowC_AV = Application.WorksheetFunction.Match(619, Range("A" & line & ":FI" & line), 0) + 1
'On Error GoTo ErrhandlerCAV
Continue:
If errorCAV = 1 Then
c_audiovisual = 0
errorCAV = 0
Else
c_audiovisual = ActiveSheet.Cells(line+ m2, lRowC_AV).Value
End If
I've made a escape in case that this concept isn't present in that line (which sometimes occurs).
Sometimes this piece of code works, and other it doesn't.
When i'm on debug mode (pressing F8) it works. And when i use small files to look for the values it works. On bigger files sometimes don't.
Any ideas?
I faced similar issues. I fixed it with using ThisWorkbook.Sheets("MySheet").Range(...) inside the Match function. Or try ActiveWorkbook as applicable. Let me know if this worked. Curious to know.
Btw I noticed column and row number both are "line". Is that a mistake?