I have searched far and wide, but can't find an answer to this simple question. I want to make a custom function in excel which will create a hyperlink.
Excel has a built in hyperlink function that works like this:
=Hyperlink(link_location, display_text)
I want to create a function called CustomHyperlink which takes one parameter, and returns a hyperlink to a google query with that parameter. Just for the sake of the question, lets assume that the passed parameter is a alphanumeric string, with no spaces.
Essentially, calling
=CustomHyperlink("excel")
should be the same as calling
=Hyperlink("http://www.google.com/search?q=excel", "excel")
This seems like such a simple task, but I absolutely cannot find a way to make this function.
Can anyone offer some quick help?
I can offer a partial solution, one that will update an existing hyperlink. This only makes sence if you are using it like, say
CustomHyperlink(A1)
were A1 contains the required serch term
To use,
enter your UDF formula in a cell, eg =CustomHyperlink(A1)
create a hyperlink on the cell (right click, Hyperlink...) . This can be any hyperlink, valid or invalid
put the required search term in the referenced cell, eg in A1 put excel
When the UDF runs it will update the hyperlink to Google the entered search term
Function CustomHyperlink(Term As String) As String
Dim rng As Range
Set rng = Application.Caller
CustomHyperlink = Term
If rng.Hyperlinks.Count > 0 Then
rng.Hyperlinks(1).Address = "http://www.google.com/search?q=" & Term
End If
End Function
In VBA editor you can use
ThisWorkbook.FollowHyperlink Address:=(strWebsite), NewWindow:=True
Which will take you to that specific website, and just build a function around that to navigate you to the site you need.
Nice idea although this isn't possible.
You seem to want to have the formula of the cell as one thing (your custom function call) and yet have the value as another (the hyperlink / URL) which simply isn't possible.
The correct way through VBA to add a hyperlink is to use the Hyperlinks property but it is not possible to call this property, through a Worksheet UDF (because of the reason above).
What is wrong with just using the the built-in =Hyperlink() worksheet function? You could effectively parameterise your URL as follows (where cell A1 = Excel):
=HYPERLINK("http://www.google.com/search?q="&A1)
You can't do this directly for the reasons creamyegg suggests, but there is a way to achieve the functionality albeit with a bit of a performance consideration.
You could use the Worksheet_Change event to track for the presence of your UDF then process the hyperlink addition there.
You would need to set up an empty function to allow this to happen, otherwise Excel will throw an error whenever you entered =CustomHyperlink... in a cell.
The below should work, not really had time to test.
Private Sub worksheet_change(ByVal target As Range)
Dim SearchValue As String
If LCase(Left(target.Formula, 16)) = "=customhyperlink" Then
SearchValue = Mid(target.Formula, 19, Len(target.Formula) - 20)
target.Value = SearchValue
target.Hyperlinks.Add target, "http://www.google.com/search?q=" & SearchValue, , "Search Google for " & SearchValue, SearchValue
End If
End Sub
The performance consideration is of course the volatile Worksheet_Change event as this can really kill large, complex workbooks.
Related
I´m using an Excel workbook with a custom formula for taking a value from the previous worksheet. I use this formula like INDIRECT(SHEETNAME(SHEET(A1)-1)&"!A1"), so SHEET(A1) returns the current sheet number, and SHEETNAME(SHEET(A1)-1) returns the name of the previous sheet, then I use INDIRECT to take the value A1 from that previous sheet.
Here is the code for the custom sheetname formula:
Function SHEETNAME(number As Long) As String
SHEETNAME = Sheets(number).Name
End Function
The problem is that when I use other workbook at the same time, the mentioned command returns #VALUE!.
Thanks for the help! :)
You should always fully qualify.
So instead of Sheets(number).Name, try ThisWorkbook.Sheets(number).Name
Not doing so can lead to bugs that are difficult to diagnose.
I would always suggest avoiding "ActiveWorkbook" unless you specifically need it.
I use popular custom function which I found on the internet on one of vba blogs. It reads text cell as if it be formula (i.e. "=A2+B2" or "=ABS(A2+B2)", I created them by using CONCATENATE function, in workbook they are without quotation marks). The code goes:
Function Eval(Ref As String)
Application.Volatile
Eval = Evaluate(Ref)
End Function
In my workbook I have multiple sheets which are exact same copies except 2 columns of data, which calculate some descriptive statistics (i.e. sum, average, standard deviation etc.), the formulas are in my source sheet, copied sheet have formula like: Eval(sourceSheet!A1) and A1 contains text of formula like above. The problem is that to apply macro after loading it, I need to pres F9 to refresh (sometimes several times). It makes refreshing ALL my copied worksheets with the data I have in worksheet I am refreshing. So for example: if i refresh in worksheet 3 and sum of data was 5 it changes sum to 5 in all other sheets. I guess somehow my code makes the function applied to entire workbook instead of single worksheets like every other excel function.
So I have 2 questions:
Is there any way to change the code so my custom function will only apply to worksheet I put it in?
Can you post me a macro code for refreshing entire workbook with every single click of left mouse button?
Thank you in advance
Thats a rather buggy UDF: Evaluate always takes unqualified references as referring to the active sheet.
You really need to use Worksheet.Evaluate. Try something like this that assumes that any unqualified references in Ref are to the sheet that Ref is on
Function Eval(Ref As range)
Application.Volatile
Eval = ref.parent.Evaluate(Ref.value)
End Function
Or if you want it to refer to the sheet that the UDF is being called from try this
Function Eval(Ref As variant)
Application.Volatile
Eval = Application.Caller.Parent.Evaluate(Ref)
End Function
There are also a number of strange things/Quirks/bugs with evaluate you should be aware of: see my blog post
https://fastexcel.wordpress.com/2011/11/02/evaluate-functions-and-formulas-fun-how-to-make-excels-evaluate-method-twice-as-fast/
I'd like to preface this question by saying that I am an undergrad in college who knows C++ and has a very rudimentary understanding of VBA.
Now then, as stated in the title I need some help configuring some VBA code for an Excel worksheet so that whenever a cell in a column (specifically the D column) is modified it will automatically update other cells within the same row.
Essentially I want this to work such that when user Bob modifies cell D26 (for example) it will call a custom function I built and insert that code into cell B26 and then repeat with a different function for cell C26.
However, this function needs to be such that if cell D27 is modified it will only modify other cells in row 27, leaving row 26 and prior or subsequent rows alone until such a time as this function is called in D28 and so on.
I'm not entirely sure if this is even possible but I'd be gracious if anybody could help me configure this.
The code I built/scavenged from the internet for my custom function is this:
http://pastebin.com/RE0V2nrT
The second function I want to call for this project is the =TODAY() function built into Excel.
The code I have scraped together so far for checking if the cell has changed is this:
http://pastebin.com/S5E8cmty
If anybody could help me understand how to write what I'm looking for it would be much appreciated. If you have a different approach to solving the issue I would also love to hear it... as long as you could help me then enact your solution, haha!
Anyways, thanks to anybody who replies.
Have a look at the worksheet events available within the Excel namespace.
For this, you would use the Change event
If you double click on the worksheet you want to monitor, you can insert a Worksheet_Change sub. Then you can use the intersect function to check if the changed cell was within your range you want to monitor (e.g. D:D).
You can specify which cells you want to change. Here I just gave an example based on what you asked. This will put the output of your function into cell B[R] and put the current date into cell C[R]. Note that I'm using the Now() function since there is no Today() function in VBA. Since this returns both date and time, I'm using the Format function to get just the date.
Just for fun, let's go a little further into the object model and first get the Worksheet object to which the target range belongs. This is not 100% necessary - you could just rely on ActiveSheet. Now, you probably don't need to do this, and it's mostly just for fun, but it's also worth noting that if you were programmatically making changes to this sheet, but had not activated this sheet first (so another sheet was active) and you had not turned off EnableEvents you would get some strange results :)
Private Sub Worksheet_Change(ByVal Target As Range)
Dim TargetSheet As Worksheet
Set TargetSheet = Target.Parent
With TargetSheet
If Not Application.Intersect(Target, .Range("D:D")) Is Nothing Then
.Cells(Target.Row, 2) = ExtractWindowsUser()
.Cells(Target.Row, 4) = Format(Now(), "YYYY-MM-DD")
End If
End With
End Sub
Explanation
Worksheet change sub is declared like this. The Worksheet objects have pre-defined method stubs for events. Kind of like an interface, though not listed as an interface in the documentation. If you think of it in that concept, this is your event handshake. See the link I posted above for a list of the worksheet events available.
Private Sub Worksheet_Change(ByVal Target As Range)
In the next lines we are getting the worksheet object to which the object named Target belongs. You can see in the sub declaration that Target is declared as an object of the type Range. If you check out the Worksheet object (linked above) or the Range object documentation you'll see that the range object is a member of the worksheet object, and the documentation kind of sucks here, but FYI the worksheet object is contained within the Parent property. Now, originally I had my code using the ActiveSheet member of the Application object - but I've edited it for the reasons given in my answer above.
Dim TargetSheet As Worksheet
Set TargetSheet = Target.Parent
I use With Blocks to save typing the same Worksheet reference in multiple places. A With block just lets me access the members of the namespace specified (in this case members of the object TargetSheet) by typing .SomeMember. The compiler understands that every reference like this refers to whatever is specified in the opening With .... statement. I personally like this for readability, but I also recommend it for maintenance (change reference one place vs many). Also having a single reference gives a tiny, insignificant, probably not worth mentioning performance boost over multiple references as well.
With TargetSheet
Next we check whether or not Target is within the range of cells we want to watch. The If....Then should look familiar enough. For our condition we use the boolean operator Not to check if the result of the intersect function (linked above) Is Nothing. The reason we do this is to check if the return is allocated. If an object is allocated the Not SomeObject Is Nothing condition will evaluate to False. If the object is not allocated (i.e. our Intersect function failed to return anything) then the statement evaluates to True. So, from the Intersect function documentation we know that if our return is allocated, the ranges intersect and the intersecting range object was returned. Thus if we want to know if they intersect, we can just check for the opposite of a failure.
If Not Application.Intersect(Target, .Range("D:D")) Is Nothing Then
The next lines then just execute some code on cells within the same row as Target. We use the Cells member of the worksheet object to specify what cells to modify. Per the documentation, the default property for Cells is Item which lets us access a range object through a row and column index like this: .Cells[Row,Column]. So, I simply use the row of our Target object and the column you wanted (column "A" =1, "B"=2, etc. You can see this by changing excel properties to R1C1 reference style if you are interested).
.Cells(Target.Row, 2) = ExtractWindowsUser()
And I think the Format() and Now() functions are pretty well explained in the documentation.
Sub TEST()
If cells(i, "R").Value <> "UK" Then
cells(i, "R").Interior.ColorIndex = 3
End If
End Sub
If I run this program it throws application defined error \
I am new to Excel (beginner)
How to correct this error!!!
Thanks In advance
I think the issue is "R" that I know of the cells method takes 2 parameters one is rows the other is columns (in that order) but this is done by number not letter so if you change it to cell(1,18) then the code above works fine.
This link may also be useful to learn more, among other things it describes how you would normally select a range first as I believe your code above will assume the currently selected page, however you might want to run in on a button click from another page or as soon as the spreadsheet opens.
http://msdn.microsoft.com/en-us/library/office/ff196273.aspx
The problem is that the variable i has not been assigned a value. VBA assumes that it is zero. Since i is used to determine the row of the cell, Excel throws an exception because there is no row 0!
First you have to define i variable
for example: Dim i as variant
I have a named comboBox, let's call it: "comboBox1"
I want to reference the value of comboBox1 from a cell.
=if(comboBox1.Value=1,1,0)
The idea above is what I'm looking for. I know I can attach an even to comboBox1, which populates a cell, which can be read by other cells, but that just introduces more moving parts and complexity.
This has to be possible, right? Any help would be great, thanks!
I think something like this is possible.
For your combobox change event, you will need to trigger a recalculation:
Private Sub ComboBox1_Change()
Application.Calculate
End Sub
Next, you will need to add a custom user defined function. The important piece of this the Application.Volatile line. This will make sure its recalculated, after any calculation.
Function GetComboVal(cmbName As String) As String
Application.Volatile 'will always recalculate
Dim cmb As OLEObject
Set cmb = Sheet1.OLEObjects(cmbName)
GetComboVal = cmb.Object.Value
End Function
So in your cell, you will need to use a call like this:
=if(GetComboVal("ComboBox1")=1,1,0)
The Downside to this technique is that if your worksheet has many calculations, it could take a while to recalculate.
Good Afternoon,
There is a much easier way to link a cell to a combo-box. With-in the properties of the ComboBox, above ListFillRange is Linked Cell. You would just designate this cell to whatever you want your combobox value to equal too.
Excel allows a cell link on both an ActiveX and a forms doropdown (combo). This will write the value to a cell without any code.