VBA: Extracting coordinates of an active cell - excel

I am new to Excel VBA and what I want to do is the following.
Currently the cell "F3" is active, and I would like to know if there is a function
that returns the value "F3".
I imagine that there is a way to extract the 'coordinate' of F3 as (6,3) since F is the 6th letter and 3 is simply 3 (maybe (3,6) if it counts row first and columns later).
If it can return something like (F,3) it would be even better, and best case scenario, F (the column LETTER) by itself.
It is imperative that I am able to extract the column letters because I intend to use this as an input to "replace all letter A to letter B".
If you have an exact answer that would be great, but if you could guide me towards a useful link that would be appreciated, too.
Thank you!!

Try below sub-
Sub GetCellAddress()
Dim x As Variant
x = Split(ActiveCell.Address, "$")
MsgBox x(1) & "," & x(2)
End Sub
Result in message box: F,3

Related

How to extract the six digit number in a cell string?

I have a column with data:
New York is really nice, 456983 Good food
Beijing is awesome 678932, Nice culture.
... and so on
I want to extract the six digit numbers and place it in a column beside the original column.
There are n rows.
Is there any way to do this with a formula, without VBA?
Without VBA, you can use the following Excel formula assuming A1 is the cell containing the text.
=MID(A1,FIND("------",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"0","-"),"1","-"),"2","-"),"3","-"),"4","-"),"5","-"),"6","-"),"7","-"),"8","-"),"9","-")),6)
This formula works for both of your examples:
=MID(A1,MIN(FIND({0,1,2,3,4,5,6,7,8,9},A1&1234567890)),6)
You can use this, enter as an array formula:
=MID(A2,MIN(IFERROR(FIND({0,1,2,3,4,5,6,7,8,9},A2),"")),SUMPRODUCT(--ISNUMBER(MID(A2,ROW($A$1:$A$200),1)+0)))
This works for me. This will look for all digits in the string. - You can of course add limitations.
Sub numberExtract()
x = ActiveCell
Dim valIs As String
Dim a As String
For i = 1 To Len(x)
a = Mid(x, i, 1)
If IsNumeric(a) Then
valIs = valIs & a
End If
Next i
MsgBox valIs
End Sub

Find and replace with column using VBA

I was wondering if there was a way to accomplish this task. I have column A and B. Column A1 contains a text value "Shared Service". Column B1 contains the text value "Shared".
What I want to do is remove the "Shared" part of "Shared Service" so all that's left is "Service". I need to do this for many different values in column A/B though.
Is there any easy way to automate this? It's basically just a mass find and replace with a blank value, it just needs to be based off the values in column B.
UPDATE:
Thanks for the replies but these solutions assume the columns line up side to side. To clarify, I need to look for ALL values in column B and remove ALL of them from column A. So the "of vat" line would become "of" in this example (it finds the "vat" value from column B and removes it from A). This has to be done with 1000s of different values.
Thanks in advance for any help provided.
I could be wrong, but it sounds like you might want a collection. I see something like this as a starting point:
Sub RemoveWords(DeleteFromCol As Range, FindCol As Range)
Dim words As New Collection
Dim r As Range
Dim word As Variant
For Each r In FindCol
words.Add (r.Value2)
Next r
For Each r In DeleteFromCol
For Each word In words
r.Value2 = Replace(r.Value2, word, "")
Next word
Next r
End Sub
And then you could invoke it with aribitrary ranges, in your example:
RemoveWords Range("A1:A11"), Range("B1:B8")
I'm guessing this may not be 100%, as in your example I would purge both words in some cases, since they exist in the "one word" list. You can handle that however you want.

How to compare a string within a string list in Excel

There are some food names and prices as you can see between I2 and J22. For instance AYÇICEK YAĞI(SUNFLOWER OIL IN ENGLISH) is 4$ per kg. In the left of the sheet, you can see other list. What I need is;
I want to compare all A* columns with Strings between I2:I22 and get the price which is written between J2:J22 then write it to the D* columns.
There are more than 500 rows and I need to do it for all rows.
And there are some headings as u can see in bold font, they should be protected.
You seem to have come up with a formula; now you need a way to dispense it. Your worksheet design does not lend itself to simply filling down a formula. However, with the numbers in column C identifying valid entries that require a formula in columns D and E, a short sub procedure can make quick work of putting the formulas into the correct places.
Sub fillFormula()
Dim w As Long, vWSs As Variant, vFRMLs As Variant
vWSs = Array("ogle_aksam_gramaj", "kahvalt" & ChrW(305) & "_gramaj", _
"araogun_gramaj")
For w = LBound(vWSs) To UBound(vWSs)
With Worksheets(vWSs(w))
With .Columns(3) '<~~ going to look at column C for numbers
With .SpecialCells(xlCellTypeConstants, xlNumbers)
.Offset(0, 1).FormulaR1C1 = _
"=IFERROR(VLOOKUP(RC1, 'urunler'!C1:C2, 2, FALSE), """")"
.Offset(0, 2).FormulaR1C1 = _
"=IFERROR(RC4*RC3, """")"
End With
End With
End With
Next w
End Sub
The IFERROR function has been used to 'wrap' the lookup and mulltiplication formulas. It catches errors and offers alternative results; in this case, zero-length strings that look blank.
The kahvaltı_gramaj worksheet causes problems in VBA due to the unicode character. You might try other methods of cycling through the worksheets.
      
That binary (macro-enabled) workbook is available from my own public dropbox here.
In the workbook you have attached, VLOOKUP will return #N/A when there is no available value.
In Sheet ogle_aksam_gramaj Cell D4 use the following Formula:
=SUMIF($I:$I,$A4,$J:$J)
You can then drag it down and it should be giving you the prices based on the details provided in the same sheet (Range I:J)
The good thing (or bad, depends on you) of sum if is that it will return 0 if there is nothing to sum. in your sheet, the items must be unique in the list, otherwise, it will keep summing every instance. So if AYÇICEK YAĞI is there 2 times, it will be summed twice.
You can use Advanced Filter with (unique values only) to make sure that all the ingredients are accounted for and are mentioned only once.
Thanks.

If values in Column B = specific text, insert specific text into a value in Column A

Simply - if any cell in Column B contains thisvalue then append to the adjoining cell in Column A with sometext.
How is this done?
A simple if statement. For example:
=IF(ISNUMBER(SEARCH(thisvalue, B1)), sometext, "")
EDIT: The ISNUMBER(SEARCH(thisvalue, B1)) searches for thisvalue in B1, and if it finds it, it returns a number (that number being the starting index of thisvalue within B1).
EDIT #2: To append the inserted value to the end of the current value in cell A, use the CONCATENATE formula.
Example:
=CONCATENATE(A1, sometext)
Put this formula in A1, then drag down as necessary:
=IF(B1="thisvalue","sometext","")
EDIT
Using a the Visual Basic Editor, you can update the contents of cell A like this:
Private Sub UpdateColumnA()
Dim x As Long
For x = 1 To 65536
If InStr(1, Sheet1.Range("$B$" & x), "thisvalue") > 0 Then
Sheet1.Range("$A$" & x) = Sheet1.Range("$A$" & x) & "sometext"
End If
Next
End Sub
Repeated runnings of the macro, however, will append the text again; you'll need more validation code if you don't want this to happen.
copy-paste in A1 , considering that you have values in B
=IF(ISNA(VLOOKUP("thisvalue",B:B,1,FALSE)),"",VLOOKUP("thisvalue",B:B,1,FALSE)&"ADDITIONAL VALUE")
it is saying:
if value of vlookup is is empty (if lookup returns nothing) , then show empty value ( double quotes)
but if the value of lookup returns something, then do this lookup and append "ADDITIONAL VALUE" text to found result
I think I have what you are looking for, let me know if you are still interested and if you want me to elaborate further. This formula in cell F2: =IF(ISNUMBER(SEARCH($U$2,E:E)),$V$2,"")&IF(ISNUMBER(SEARCH($U$3,E:E)),$V$3,"")&...
where you are searching for a value that you specify in U2 across all cells in column E:E, if it finds a match it appends the value you specify in V2. To search for multiple words assigning corresponding value simply concatenate as shown as much as you like. I am able to specify hundreds of words (and corresponding values). I hope it helps.

Extract the last substring from a cell

I have names in a column. I need to split just the last names from that column into another column.
The last name is delimited by a space from the right side.
The contents in cell A2 = Alistair Stevens and I entered the formula in cell B2 (I need 'Stevens' in cell B2)
I tried using the following formulas:
=RIGHT(A2,FIND(" ",A2,1)-1)
=RIGHT(A2,FIND(" ",A2))
Both these formulas work for this cell but when I fill it down / copy and paste it for the cells below it doesn't work. I get the wrong values!!
A3 -> David Mckenzie
B3 -> Mckenzie
This works, even when there are middle names:
=MID(A2,FIND(CHAR(1),SUBSTITUTE(A2," ",CHAR(1),LEN(A2)-LEN(SUBSTITUTE(A2," ",""))))+1,LEN(A2))
If you want everything BUT the last name, check out this answer.
If there are trailing spaces in your names, then you may want to remove them by replacing all instances of A2 by TRIM(A2) in the above formula.
Note that it is only by pure chance that your first formula =RIGHT(A2,FIND(" ",A2,1)-1) kind of works for Alistair Stevens. This is because "Alistair" and " Stevens" happen to contain the same number of characters (if you count the leading space in " Stevens").
The answer provided by #Jean provides a working but obscure solution (although it doesn't handle trailing spaces)
As an alternative consider a vba user defined function (UDF)
Function RightWord(r As Range) As Variant
Dim s As String
s = Trim(r.Value)
RightWord = Mid(s, InStrRev(s, " ") + 1)
End Function
Use in sheet as
=RightWord(A2)
Try this function in Excel:
Public Shared Function SPLITTEXT(Text As String, SplitAt As String, ReturnZeroBasedIndex As Integer) As String
Dim s() As String = Split(Text, SplitAt)
If ReturnZeroBasedIndex <= s.Count - 1 Then
Return s(ReturnZeroBasedIndex)
Else
Return ""
End If
End Function
You use it like this:
First Name (A1) | Last Name (A2)
Value in cell A1 = Michael Zomparelli
I want the last name in column A2.
=SPLITTEXT(A1, " ", 1)
The last param is the zero-based index you want to return. So if you split on the space char then index 0 = Michael and index 1 = Zomparelli
The above function is a .Net function, but can easily be converted to VBA.
If you want to get the second to last word in a text, you can use this macro as a function in your spreadsheet:
Public Function Get2ndText(S As String) As String
Dim sArr() As String
Dim i As Integer
sArr = Split(S, " ")
'get the next to the last string
i = UBound(sArr) - 1
Get2ndText = sArr(i)
End Function
Then in your spreadsheet B1 as the text:
CURRENT OWNER 915 BROADWAY ST HOUSTON TX 77012-2126
in B2 your formula would be:
=Get2ndText(B1)
The result would be
TX
Simpler would be:
=TRIM(RIGHT(SUBSTITUTE(TRIM(A2)," ",REPT(" ",99)),99))
You can use A2 in place of TRIM(A2) if you are sure that your data doesn't contain any unwanted spaces.
Based on concept explained by Rick Rothstein:
http://www.excelfox.com/forum/showthread.php/333-Get-Field-from-Delimited-Text-String
Sorry for being necroposter!
Right(A1, Len(A1)-Find("(asterisk)",Substitute(A1, "(space)","(asterisk)",Len(A1)-Len(Substitute(A1,"(space)", "(no space)")))))
Try this. Hope it works.
Try this:
=RIGHT(TRIM(A2),LEN(TRIM(A2))-FIND(" ",TRIM(A2)))
I was able to copy/paste the formula and it worked fine.
Here is a list of Excel text functions (which worked in May 2011, and but is subject to being broken the next time Microsoft changes their website). :-(
You can use a multiple-stage-nested IF() functions to handle middle names or initials, titles, etc. if you expect them. Excel formulas do not support looping, so there are some limits to what you can do.
RIGHT return whatever number of characters in the second parameter from the right of the first parameter. So, you want the total length of your column A - subtract the index. which is therefore:
=RIGHT(A2, LEN(A2)-FIND(" ", A2, 1))
And you should consider using TRIM(A2) everywhere it appears...
Try this:
Right(RC[-1],Len(RC[-1])-InStrRev(RC[-1]," "))

Resources