Find email adresses in excel workbook - vba

I have a excel sheet which containts an emails in exact one column(the order of the column is not exact and changing).
I used the find function looking like this.
Sub emialy()
Cells.Find ("#",,xlValues,xlPart,xlByRows,,,,) ActiveCell.Copy
End Sub
but I am recieving an error...
Then if a program finds where the emails list are beginning i want to copy that very first email and open an email client (outlook), create an new email and paste the exact copied email to the "to:" row.

The recommended way to use the Find function, is by setting a Range type variable to the result. This way you can trap the scenario Find was unable to find # throughout your worksheet's Cells with If Not EmailRng Is Nothing Then.
Code
Sub emialy()
Dim EmailRng As Range
Set EmailRng = Cells.Find(What:="#", LookIn:=xlValues, Lookat:=xlPart, SearchOrder:=xlByRows)
If Not EmailRng Is Nothing Then ' succesful find
EmailRng.Copy
Else
MsgBox "Could not find the # symbol"
End If
End Sub

Related

how to dynamically update a workbook name in excel using vba?

I’m trying to dynamically update a workbook name in a formula in excel to bring through data from a continually changing source file.
So far I have been getting by with using an indirect formula, but now I have a huge workbook with around 216,000 cells to populate and I don’t think indirect is the most efficient way to do this.
I want to use VBA instead but I have no experience with this. From doing some googling I have found a few things but I’m not sure how to implement my specific needs into the code.
so far 've come up with this:
Sub replace()
Dim cell As Range
cell.Formula = replace(cell.Formula, "OfficeSupplies.csv",
"OfficeSupplies2.csv")
Range("a1:d8").Value
Next
End Sub
However, when I try to execute it, it doesn't work at all.
Edited to insert the handling of a specified range instead of ActiveSheet used range and to handle a sheet different to "Active" one
To answer the question, you could use a code like the following to replace in "Active" sheet used range:
Sub replace()
ActiveSheet.UsedRange.SpecialCells(xlCellTypeFormulas).Replace(What:="OfficeSupplies.csv", Replacement:="OfficeSupplies2.csv", LookAt:=xlPart)
End Sub
or you could explicitly refer to a sheet:
Sub replaceInSpecifiedSheet()
Worksheets("MySheetName").UsedRange.SpecialCells(xlCellTypeFormulas).Replace(What:="OfficeSupplies.csv", Replacement:="OfficeSupplies2.csv", LookAt:=xlPart) ' change "MySheetName" to your actual sheet name
End Sub
or you could want to change formulas in a given range:
Sub replaceInSpecifiedRangeOfSpecifiedSheet()
Worksheets("MySheetName").Range("A5:B8").SpecialCells(xlCellTypeFormulas).Replace(What:="OfficeSupplies.csv", Replacement:="OfficeSupplies2.csv", LookAt:=xlPart) ' change "MySheetName" to your actual sheet name
End Sub
But changing a formula in 216k cells can be quite a time consuming activity
You may consider the opposite: change the name of the”continually changing source file”
You can do that without VBA of course
Should you be “forced” to or prefer use VBA then you could use ‘Name ... As‘ statement
Sub replace2()
Dim FullNameToChange As String
Dim HardCodedFullName As String
FullNameToChange = "C:\ChangingName.xls"
HardCodedFullName = "C:\HardCodedName.xls"
If Dir(FullNameToChange) <> "" And Dir(HardCodedFullName) = "" Then Name FullNameToChange As HardCodedFullName
End Sub
Give this a try
Cells.Replace "OfficeSupplies.csv", "OfficeSupplies2.csv", xlPart, , True

VBA Search Range for text then run macro

I'm trying to write a VBA macro (which I'll attach to a command button) which searches K7 through K13 to find "Sheet1", "Sheet2", "Sheet3", or "Sheet4" Only one answer is possible based on pre-existing If/Then statements.
When it finds "Sheet1" I want it to run macro "GoToSheet1"
When it finds "Sheet2" I want it to run macro "GoToSheet2"
When it finds "Sheet3" I want it to run macro "GoToSheet3"
When it finds "Sheet4" I want it to run macro "GoToSheet4"
Basically i have four possible conditions which could exist based on how someone answers two yes/no questions. That is what the initial if/then statements cover. However, I cannot get the VBA macro to search across the cell range K7 through K13 for any one of the four text phrases.
Surely you can loop thru the range K7:K13 for checking each cell values. However using Range.Find method would be a better way to do this.
Private Sub CommandButton1_Click()
Dim lookingRange As Range
Set lookingRange = Range("K7:K13")
If Not lookingRange.Find(What:="Sheet1", LookIn:=xlValues) Is Nothing Then GoToSheet1: Exit Sub
If Not lookingRange.Find(What:="Sheet2", LookIn:=xlValues) Is Nothing Then GoToSheet2: Exit Sub
If Not lookingRange.Find(What:="Sheet3", LookIn:=xlValues) Is Nothing Then GoToSheet3: Exit Sub
If Not lookingRange.Find(What:="Sheet4", LookIn:=xlValues) Is Nothing Then GoToSheet4: Exit Sub
MsgBox "not found"
End Sub

VBA- Using inputbox to filter and copy data

i am working on a userform where i puted a button that when i click on it i got an input box where i try to filter data of the column (E) then after filtering this data copy from colum A1 till the value filtered in the column E in another sheet caaled filtred_data i am using this code this code but it show me a bug dont nw how to fix it
Private Sub CommandButton9_Click()
Dim xno As Integer, Found As Range
Do
xno = Application.InputBox("Enter the number of Top communities ", Type:=1)
If TypeName(xno) = "Boolean" Then Exit Sub
Set Found = Columns("E").Find(what:=xno, lookat:=xlWhole, LookIn:=xlValues)
If Found Is Nothing Then
MsgBox "the number was not found, please try again !!", vbInformation
Else
Found.Range("A1:F10000").Copy Destination:=Sheets("filtred_data").Range("A1:F10000")
End If
Loop
End Sub
if anyone can help me please , thank you
The problem in your case is that you are setting the Found variable to be a single cell by using the Find method. Later in your code, you are trying to copy the A1:F10000 of that ONE cell when you write Found.Range("A1:F1000").
Essentially, your code looks like this (assume Found refers to cell E25):
Range("E25").Range("A1:F1000").Copy
Can you see why that would cause an error?
I'd try to offer more help, but it's hard to determine exactly what you want. Can you possibly give more details about your spreadsheet layouts and an example of what you want to happen?

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.

VBA Referring to a cell using Sheet Name not working properly

Summary: I am writing a macro that takes names from many different sheets in an excel file and compiles them together on a "master list", but I'm having trouble with referencing a cell on another sheet.
The Problem: When I refer to a specific cell using the sheet name as reference with Sheets("MasterList").ActiveCell.Offset(0, 1), nothing gets picked up. However, when I remove Sheets("MasterList") the macro works fine (the macro is currently on "MasterList" at the time which is the only way this would work). Also, the spelling for the name of the sheet was correct in my code.
Question: Why is this happening? The logic behind the code seems sound, and I'm spelling my sheet name correctly.
Code:
Do
If Sheets("MasterList").ActiveCell.Offset(0, 1) = firstName Then 'IF FIRST AND LAST NAMES MATCH, EXIT THE CHECK
Exit Do
End If
On Error Resume Next
Cells.Find(What:=lastName, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
Loop Until Err.Number > 0
ActiveCell is a property of the Application object, not a Sheet.
There is only one ActiveCell, and it is the active cell on the currently active sheet.
It's not entirely clear what you are trying to do. But in general you should avoid Select and Activate with this sort of code. Use instead somthing like:
Dim wsMasterList as Worksheet
Set wsMasterList = Thisworkbook.WorkSheets("MasterList") ' assuming the vba code is in the workbook containing MasterList
To track the last used cell in MasterList use a variable like
Dim rMasterList as Range
Set rMasterList = wsMasterList.Cells( ... ' Specify the cell you want
Then use rMasterList.Offset(0, 1) to refer to cells relative to that cell
Searching on MasterList use:
Dim cl as Range
Set cl = wsMasterList.UsedRange.Find( ... )
If Not cl Is Nothing Then
' cl will be Nothing if the search term is not found
' ...