I have a column which is populated using Index and Match functions and it results in a N/A value when the value is not found. I want to be able to replace all such error values from the column by a special value. I want to do this in VBA code. Any help?
I do not want to rewrite the function with an IF logic.
You really could do this without VBA, by the following:
IFERROR(myIndexMatchFormula,"special value")
If you really need a VBA solution, try something like the below. It will find all the error cells in your range and replace with something of your choice. No If statements, no loops!
Option Explicit
Sub replaceErrors()
Dim rng As Range
On Error Resume Next
Set rng = Range("A1:A10").SpecialCells(xlCellTypeFormulas, 16) ' -> replace with your specific range
rng.Value = "special values" '-> place what you want here
On Error GoTo 0
End Sub
Columns("E").SpecialCells(xlCellTypeFormulas, xlErrors).Value = ""
can replace all errors in column E, as an example.
However, unfortunately, specialcells always throws an error if it finds nothing, so you must catch this error via some on error ...
If r is the range which needs to be examined, you can always use the following to identify if the value in the cell is "N/A"
If r.Value = CVErr(xlErrNA) Then
... ' do something
Else
... ' do something else
Endif
Related
I am new to VBA and trying to autofilter a column range. The column is named "Vlookup" and sits at index position 27.
rData.AutoFilter field:=27, Criteria1:="Class" ' filter criterion
In order to make this dynamic, I need to be able to filter according to column name rather than column index.
However, when I do
rData.AutoFilter field:=Application.Match("Vlookup", Selection.Rows(1), 0), Criteria1:="Class" ' filter criterion
I yield
Runtime Error '424' - Object Required
How to correctly Autofilter by column name in VBA?
Not sure what option you went with but we had a similar issue and we discovered that it is as easy as using a table for your data then use Field:=Listobject.ListColumns("Column Name").Index. This way your solution is dynamic.
Set rData = Workbooks("Workbook Name").Worksheets("Sheet Name").Listobjects("Table Name")
rData.DataBodyRange.AutoFilter field:=rData.ListColumns("Vlookup").Index, Criteria1:="Class"
You can use helper UDF which will return column's index:
Function GetIndex(colName As String)
GetIndex = WorksheetFunction.Match(colName, ActiveSheet.AutoFilter.Range.Rows(1), 0)
End Function
UPD
You can substitute ActiveSheet with your sheet.
You can use the Find function to find "Vlookup" in the header row, and then retrieve the numeric value of the Column.
Note: there's no need to use Selection, instead fully qualify your Rows(1) with your rData sheet object (use the With rData statement).
See code and comments below:
Dim FindRng As Range
Dim FiltCol As Long
With rData
Set FindRng = .Rows(1).Find(what:="Vlookup")
If Not FindRng Is Nothing Then ' Find was successful
FiltCol = FindRng.Column ' get the column number where "Vlookup" was found
Else ' find unable to find "Vlookup"
MsgBox "Find Error!"
Exit Sub
End If
.AutoFilter Field:=FiltCol, Criteria1:="Class" ' filter criterion
End With
I am trying to use Excel VBA to count the number of rows until I hit a specific string and set a variable equal to it.
Something like:
Dim i as Integer
i = Worksheets("Scope Phase Document").Range("A1", Range("A1").End(xlDown)).Find("FACTS - What are we measuring?").Count
I know this isn't the correct syntax and I'm probably missing other stuff, but just using the different functions I currently know, this is what I would hope would do the trick. I get
Run-time error '91' saying "Object variable or With block variable not
set
I have tried a few different ways of doing it, but can't figure out a way that doesn't result in an error.
So I want to start at A1 and count all the rows down until I reach the specific string "FACTS - What are we measuring?".
Any help would be greatly appreciated!
I prefer MATCH, but if the match is not found it throws an error. So we need to test for that:
Dim i As Long
i = 0
On Error Resume Next
i = Application.WorksheetFunction.Match("FACTS - What are we measuring?", ActiveSheet.Range("A:A"), 0)
On Error GoTo 0
If i > 0 Then
' do you stuff with i
End If
So you basically want MATCH():
=MATCH("FACTS - What are we measuring?",A:A,0)
It returns the row number of matched string.
Your code is fine except you should use the Row property. The Count property as you have used it will return 1 because the Find method returns one cell (the first cell where a match is found).
Dim i as Integer
i = Worksheets("Scope Phase Document").Range("A1", Range("A1").End(xlDown)).Find("FACTS - What are we measuring?").Row
Like Scott mentioned, if your text is not found, Excel will throw an error.
I'd do this:
Sub rowcounter()
Dim i As Integer
Range("A1").Select
i = 0
Do
Selection.Offset(1, 0).Select
i = i + 1
Loop Until Selection.Value = "FACTS - What are we measuring?"
MsgBox "rows count is " & i
End Sub
I have a list of values, and in a table, I have those same values spread out.
I need some sort of loop that can search the 1x20 list and print the first value that is not already in the table, without having to write numerous countif() statements. Is there a way to do this faster?
Sure you need a loop of a range of cells and test if value exists. You'd need to post more of your code to give a specific example but this should get you started:
Sub LoopExampleUsingRange()
Dim aCell As Range
For Each aCell In ActiveSheet.Range("A1:A20").Cells
If InStr(1, "SOME TEXT/table/OR A CELL VALUE TO S", aCell.Value) Then
'if it exists put here
'Perhaps do nothing?
Else
'if doesn't exist put some code here.
End If
Next aCell
End Sub
I'm having a problem where moving a VLookup function from a Cell to a Macro is returning #N/A.
Right now, I have a table that is referencing a second, unformatted table to build a formatted list. The formatted list uses a series of VLOOKUP commands to populate, but this requires manually entering a new line and the 'SubPart' name.
I'm writing a macro that will simply read the whole source table and populate thew new formatted one with a single click.
Unfortunately, I can't seem to get VLOOKUP to work when it's taken from cells to a macro.
Sub PopulateSubs()
On Error GoTo MyErrorHandler:
Dim SubAssy, SubPart As String
Dim BomCount, i As Integer
Dim BlankRow As Long
Dim Source_Table As ListObject
Set Source_Table = Worksheets("BoMs").ListObjects("Table_Query_From_Syspro")
SubAssy = InputBox("Enter the Subassembly:")
If Len(SubAssy) > 0 Then
BomCount = Application.CountIf(Range("Table_Query_from_Syspro[ParentPart]"), SubAssy)
For i = 1 To BomCount
BlankRow = Range("A10000").End(xlUp).Row + 1
Cells(BlankRow, 1).Select
SubPart = SubAssy & i
ActiveCell = i
ActiveCell.Offset(0, 1).Select
ActiveCell = Application.WorksheetFunction.VLookup(SubPart, Source_Table, 2, 0)
ActiveCell.Offset(0, 1).Select
ActiveCell = Application.WorksheetFunction.VLookup(SubPart, Source_Table, 3, 0)
Next i
Else
MsgBox "You entered an invalid value"
End If
MyErrorHandler:
If Err.Number = 1004 Then
MsgBox "Sub assembly Not Present in the table."
End If
End Sub
VLOOKUP in the manual table was correctly working, but I cannot get it to return anything but #N/A in this application.
I have looked at similar solutions on this site, and run the macro with SubPart as "SubPart" as well as ""SubPart"" but neither term seems to help.
The source table is formatted as General for all cells, I'm not sure if this causes a type mismatch with String entries.
Thanks!
This works fine
...Application.WorksheetFunction.VLookup(SubPart, Application.Range("Source_Table"), 6, False)
The way you call the vlookup doesn't work is because it is a member of Worksheetfunction, try;
Application.Worksheetfunction.VLookup
This applies to most excel formulas. There are some functions that are embedded in vba like min/max/now and do not specifically have to be called through the Worksheetfunction member.
Hello am trying to do a code like below
Do while (the selected cell is in the column b)
Code...
End Loop
Message error
When I click the button when the selected cell is not in the column b want to appear error msg
Provided that a single cell is selected, then you can achieve the desired result by using the following statement:
' get the column number
col = Selection.Column()
Column "B" corresponds to Column number 2. If selection is not in a column 2, then pop-up the Error Message (as per your requirement).
Hope this will help.
Based on your comment, you can try something like this:
Dim r As Range
'assign the selection to a variable
'but make sure it is a range
If TypeName(Selection) = "Range" Then Set r = Selection
'check if something is assigned to r; meaning a range is selected
If Not r Is Nothing Then
'check if it is somewhere in Column B
If Not Intersect(r, Sheets("Sheet1").Range("B:B")) Is Nothing Then
'do your stuff here
Else
'your error message here
MsgBox "Invalid Selection", vbCritical
End If
End If
Above code uses MsgBox to act as your error message.
Is this what you're trying? HTH.