VBA Vlookup formula, value does not appear in cell - vba

My problem is that when i put this code in VBA:
Sub formula_vlookup()
'MONTHS
ActiveSheet.Cells(ActiveCell.Row, 1).Select
ActiveCell.Offset(0, 16).Select
With ActiveCell
.formula = "=IF(ISNA(VLOOKUP(" & .Offset(0, -16).Address(0, 1) & ",'CZ support'!$A:$AA,2,0)), _
"""",(VLOOKUP(" & .Offset(0, -16).Address(0, 1) & ",'CZ support'!$A:$AA,2,0)))"
End With
End Sub
It works perfectly ( i mean , it gives me the value of the cell that is "vlooked up" but the problem is that it does not display that value in the cell, so the only way to know if its a value there is making a SUM of the cells that contain this formula.
how can i manage this problem?
Thank you in advance for your help

Things to check:
Name [CZ Support] (with a BLANK in the middle) may be invalid ... I can't create that in XLS2010
check that the name exists (Name manager or just try to select it from the drop down left of formula bar)
Try entering the same formula (with .Offset(...) expanded to actual cell addresses) directly in worksheet cell(s)
Try replacing the "" in the FALSE part of the =IF(...) by some text (e.g. "not found") to see if you're caught by an exception
Try replacing the last VLOOKUP argument (0) by TRUE or FALSE as per the documentation
Try assigning the formula to a string variable first and examine it in the debugger window (or do a Debug.Print thereof)
pasting your code "as is" gave me an error - my VBA doesn't like the line splitting underscore in the formula generation

Related

How to combine indirect and direct references in VBA?

Issue:
I need to call direct and indirect references. I have a column that shifts to the right every time the program is run. The column is being used to collect the sum of the preceding columns. (I'm aware I can combine the sheet1 within the with, however there are pieces of code between the with and sheet select and this particular question focuses on just the .value section.)
Code 1:
Sheets("Sheet1").Select
With Range("AL2")
.Value = "=SUM(B2:RC[-1])"
End With
B2 is being inserted as a string, instead of as a cell name.
I've also tried:
Sheets("Sheet1").Select
With Range("AL2")
.Value = "=SUM(range("B2") & ":RC[-1])"
End With
Sheets("Sheet1").Select
With Range("AL2")
.Value = "=SUM("& B2 & ":RC[-1])"
End With
This particular set of code does not run correctly and returns:
SYNTAX ERROR
So, the problem in this specific instance is that you are mixing R1C1 and A1 style notation.
Anyway, I'd change your code to set the .Formula property instead of the .Value property, and specifically change it to .FormulaR1C1 if you want to use that notation or leave it as .Formula for A1 notation.
Anyway, your original code:
Sheets("Sheet1").Select
With Range("AL2")
.Value = "=SUM(B2:RC[-1])"
End With
This is setting B2 as a string because Excel is recognizing the RC notation, correctly interpreting that "RC[-1]" is a cell reference, but then not understanding what "B2" means.
So, I'd use something like this:
With Sheets("Sheet1").Range("AL2")
.FormulaR1C1 = "=SUM(R2C2:RC[-1])"
End With
That however would leave $B$2 as an absolute cell reference, and AK2 as a relative reference, which is kind of gross. Depending on your needs you could do this:
With Sheets("Sheet1").Range("AL2")
.FormulaR1C1 = "=SUM(R2C2:R2C37)"
End With
Which would lead to both being absolute references.
If you want something more dynamic, you'll need to use string manipulation on the string you're inputting into the worksheet. For instance, if you have r1 as a range object (with address B2) and r2 as a range object (with address AK2), you could do this:
With Sheets("Sheet1").Range("AL2")
.Formula = "=SUM(" & r1.address ":" & r2.address & ")"
End With
If you have questions, let me know.

VBA - How to convert value of cell from text to number

I have to columns with exported numbers, which are stored as text.
I tried to convert those data to numbers with this code.
Sub FormatColumns()
Columns(9).NumberFormat = "0"
Columns(10).NumberFormat = "0"
End Sub
It has done the job correctly (or it seems so), but I am still not able to work with those data as with numbers, but Excel tell me, that it is stored as number.
But when I verify it via formula =ISTEXT(), it always shows me TRUE
Could you help me with it, please? All tutorials and advices, which I've found on Google was via Formating cells or =VALUE(), but VALUE fucntion doesnt work for me, it shows me #VALUE.
Thank you in advance!
Another solution is:
Sub Macro1()
Range("A:A").Select 'Range of values you need converted
For Each Cell In Selection
Cell.Value = (Cell.Value * 1)
Next
End Sub
A non-vba equivalent solution is to have a "1" entered in a cell, copy that cell, select the range you would like converted to numbers, right click and press Paste Special -> Multiply.
This will leave all values in that range as numbers without changing the format. Tested with ISTEXT.
Make sure your settings also match with commas replacing decimals otherwise it may continue to have issues.
you must replace "," ~~> "."
Sub FormatColumns()
With Columns("i:j")
.Replace ",", "."
.NumberFormat = "#,###.00"
End With
End Sub
Check entire relevant region is set to Number format first.
Selection the relevant region and do a global replace of for nothing ("space" to "leave empty"). Then depending upon your locale try a global replace of , to ..
Next enter 1 in a spare cell, copy that cell, select the entire relevant region and Paste Special, Option, Multiply.
If that does not work switch . back to , and repeat the Paste Special.
Its the comma, needs to be . so 405,90 = 405.90
Converting numbers stored as text to numbers via Macro
Sub macro()
Range("F:F").Select 'specify the range which suits your purpose
With Selection
Selection.NumberFormat = "General"
.Value = .Value
End With
End Sub
Hilight the numbers you with to "fix" and run:
Sub fixNumbers()
With Selection
.NumberFormat = "General"
.Value = .Value
End With
End Sub

Deleting a ' from a cell which is not being retrieved in .Value in VBA

I need to find out how to delete a ' which is at the very beginning of every cell in the A column in a Excel but I can't figure out how to do it.
If I perform a Replace with
Replace(ActiveWorkbook.Worksheets("MAIN").Cells(2, 1).Value, "'", "")
or just showing the cell value with a MsgBox it just shows the number itself, without the '.
Any idea about how to delete that character if I couldn't even access it?
P.S: I've tried a basic "find and replace" with same result, even saying I have no matches...
Thanks in advance.
EDIT: Pressing F2 on the "A2" cell to see the formula shows this:
You will not see ' in VBA, neither can you remove it with Excel replace dialog – this is a special symbol that forces numeric values to be treated as text.
You can just reassign formulas and this will remove ':
ActiveWorkbook.Worksheets("MAIN").Range("A1").Formula = ActiveWorkbook.Worksheets("MAIN").Range("A1").Formula
try this:
Sub main()
Dim cell As Range
For Each cell In Range("A1", Cells(Rows.Count, 1).End(xlUp))
cell.Value = Val(cell.Value)
Next
End Sub

VBA identify column header of highlighted cells

I'm new to VBA. I'm using an excel sheet with dropdowns selected by a user in cells A10:E10. My macro runs data validation on the information inputted by the user. If data entered does not fit parameters set by the macro, the cell is highlighted. At the end of the macro I would like a MsgBox stating that highlighted cells exist in x column/s. Here is what I have:
Sub CheckErrors()
Range("A11:E100000").Select
Dim high As Range
Dim c As Range
Set high = Selection
For Each c In high
If c.Interior.Pattern <> xlNone Then
MsgBox ("Please update highlighted cells in " & c.Column & " and run Data Validation again")
Exit Sub
End If
Next c
MsgBox ("Data verification is complete")
End Sub
Instead of saying c.Column I would ideally like the code to identify which cells are highlighted and display the column header in A10:E10. For instance, if B24 and C82 are highlighted I would like the MsgBox to state "Please update highlighted cells found in Phone Numbers and Addresses". "Phone Numbers" and "Addresses" would be the values in cells B10 and C10 respectively and would come from a dropdown list that the user previously selected.
Any help would be much appreciated. Thanks!
Easy! You've already done most of the work by getting the column, all you need to do is insert your value with the appropriate row and you've got it. Here is what your message box line should look like:
`MsgBox ("Please update hilighted cells in " & Cells(10, c.Column).value & " and run Data Validation again")`
I'm not sure how familiar you are with cells, but it is Cells(row index, column index) and using the .Value property returns the contents of that cell. Assuming that your headers are in the 10th row of your workbook, this should get you what you are looking for.

Get the cell reference of the value found by Excel INDEX function

The Problem
Assume that the active cell contains a formula based on the INDEX function:
=INDEX(myrange, x,y)
I would like to build a macro that locates the value found value by INDEX and moves the focus there, that is a macro changing the active cell to:
Range("myrange").Cells(x,y)
Doing the job without macros (slow but it works)
Apart from trivially moving the selection to myrange and manually counting x rows y and columns, one can:
Copy and paste the formula in another cell as follows:
=CELL("address", INDEX(myrange, x,y))
(that shows the address of the cell matched by INDEX).
Copy the result of the formula above.
Hit F5, Ctrl-V, Enter (paste the copied address in the GoTo dialog).
You are now located on the very cell found by the INDEX function.
Now the challenge is to automate these steps (or similar ones) with a macro.
Tentative macros (not working)
Tentative 1
WorksheetFunction.CELL("address", ActiveCell.Formula)
It doesn't work since CELL for some reason is not part of the members of WorksheetFunction.
Tentative 2
This method involves parsing the INDEX-formula.
Sub GoToIndex()
Dim form As String, rng As String, row As String, col As String
form = ActiveCell.Formula
form = Split(form, "(")(1)
rng = Split(form, ",")(0)
row = Split(form, ",")(1)
col = Split(Split(form, ",")(2), ")")(0)
Range(rng).Cells(row, CInt(col)).Select
End Sub
This method actually works, but only for a simple case, where the main INDEX-formula has no nested subformulas.
Note
Obviously in a real case myrange, x and ycan be both simple values, such as =INDEX(A1:D10, 1,1), or values returned from complex expressions. Typically x, y are the results of a MATCH function.
EDIT
It was discovered that some solutions do not work when myrange is located on a sheet different from that hosting =INDEX(myrange ...).
They are common practice in financial reporting, where some sheets have the main statements whose entries are recalled from others via an INDEX+MATCH formula.
Unfortunately it is just when the found value is located on a "far" report out of sight that you need more the jump-to-the-cell function.
The task could be done in one line much simpler than any other method:
Sub GoToIndex()
Application.Evaluate(ActiveCell.Formula).Select
End Sub
Application.Evaluate(ActiveCell.Formula) returns a range object from which the CELL function gets properties when called from sheets.
EDIT
For navigating from another sheet you should first activate the target sheet:
Option Explicit
Sub GoToIndex()
Dim r As Range
Set r = Application.Evaluate(ActiveCell.Formula)
r.Worksheet.Activate
r.Select
End Sub
Add error handling for a general case:
Option Explicit
Sub GoToIndex()
Dim r As Range
On Error Resume Next ' errors off
Set r = Application.Evaluate(ActiveCell.Formula) ' will work only if the result is a range
On Error GoTo 0 ' errors on
If Not (r Is Nothing) Then
r.Worksheet.Activate
r.Select
End If
End Sub
There are several approaches to select the cell that a formula refers to...
Assume the active cell contains: =INDEX(myrange,x,y).
From the Worksheet, you could try any of these:
Copy the formula from the formula bar and paste into the name box (to the left of the formula bar)
Define the formula as a name, say A. Then type A into the Goto box or (name box)
Insert hyperlink > Existing File or Web page > Address: #INDEX(myrange,x,y)
Adapt the formula to make it a hyperlink: =HYPERLINK("#INDEX(myrange,x,y)")
Or from the VBA editor, either of these should do the trick:
Application.Goto Activecell.FormulaR1C1
Range(Activecell.Formula).Select
Additional Note:
If the cell contains a formula that refers to relative references such as =INDEX(A:A,ROW(),1) the last of these would need some tweaking. (Also see: Excel Evaluate formula error). To allow for this you could try:
Range(Evaluate("cell(""address""," & Mid(ActiveCell.Formula, 2) & ")")).Select
This problem doesn't seem to occur with R1C1 references used in Application.Goto or:
ThisWorkbook.FollowHyperlink "#" & mid(ActiveCell.FormulaR1C1,2)
You could use the MATCH() worksheet function or the VBA FIND() method.
EDIT#1
As you correctly pointed out, INDEX will return a value that may appear many times within the range, but INDEX will always return a value from some fixed spot, say
=INDEX(A1:K100,3,7)
will always give the value in cell G3 so the address is "builtin" to the formula
If, however, we have something like:
=INDEX(A1:K100,Z100,Z101)
Then we would require a macro to parse the formula and evaluate the arguments.
Both #lori_m and #V.B. gave brilliant solutions in their own way almost in parallel.
Very difficult for me to choose the closing answer, but V.B. even created Dropbox test file, so...
Here I just steal the best from parts from them.
'Move to cell found by Index()
Sub GoToIndex()
On Error GoTo ErrorHandler
Application.Goto ActiveCell.FormulaR1C1 ' will work only if the result is a range
Exit Sub
ErrorHandler:
MsgBox ("Active cell does not evaluate to a range")
End Sub
I associated this "jump" macro with CTRL-j and it works like a charm.
If you use balance sheet like worksheets (where INDEX-formulas, selecting entries from other sheets, are very common), I really suggest you to try it.