Calling a custom built VBA function when an Excel cell is changed - excel

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.

Related

Select referenced range from non-active table via VBA in Excel

Given a certain range rngRange e.g. set rngRange = Workbooks(2).Worksheets(5).Range("C4:P49") If I use rngRange.select it will throw an error message if the table containing the range is not the active window/workbook/table (e.g. by wbWorkbook.Activate and wsWorsheet.Activate). Using rngRange.Activate by itself doesn't work (throws an error), probable a simple problem. But somehow I'm blind today.
Is it possible to "activate" the range directly without activating the workbook/worksheet first? And if not, can I get a workbook/worksheet reference from the range reference somehow (note, the whole thing is inside a function that only gets the range reference, I would like to avoid to add a wbWorkbook/worksheet reference since I have to change all function calls as well)?
rngRange.Parent 'gives you the sheet
rngRange.Parent.Parent 'gives you the workbook
So you can use them to .Activate them.
rngRange.Parent.Parent.Activate
rngRange.Parent.Activate
rngRange.Select
Alternatively as #Viktor mentioned:
Application.Goto rngRange

How to list all excel current regions in one worksheet

In order to navigate through complex spreadsheets that I'm asked to analyse I need a list of all current regions in a worksheet. Excel help does not give me many clues. My solution so far is to loop over areas using the special cells function, but it is rather slow.
Function list_all_current_regions(work_sheet)
Dim current_region_dic As New Dictionary
Set r = work_sheet.Cells(1, 1)
For Each x In Array(xlCellTypeConstants, xlCellTypeFormulas)
Set c = work_sheet.Cells(1, 1).SpecialCells(x, 23)
For Each a In c.Areas
If Not current_region_dic.Exists(a.CurrentRegion.Address) Then
current_region_dic.Add a.CurrentRegion.Address, ""
End If
Next
Next
Set list_all_current_regions = current_region_dic
End Function
Is there a smarter way to list all the current regions in a worksheet?
Over the years I've avoided having multiple ranges on Worksheets for the very reason you are asking about, and I move disconnected content onto its own Worksheet when a client gives me a model designed as a single "ubersheet".
The only way around this I've found is to use Named Ranges. They are accessed using the Names collection attached to the Workbook and Worksheet objects.
One other tip I'll give is to just used the Named Range on the top left cell only then you can use the CurrentRegion property to grab the entire range. This helps when you have expanding regions that you don't want to go in to set and reset the entire range.
https://msdn.microsoft.com/en-us/library/office/ff196678.aspx?f=255&MSPPError=-2147217396

Link ActiveX to Excel

Hope somebody can help!
I am programming in VB6 and am trying to write an activeX control for an indicator. The indicator should change color relative to an excel open workbook cell being true or false. The indicator should be auto updating i.e. the indicator needs to link live to the excel cell.
I can then place several of the indicators c/w links to different cells on a userform. The workbook is opened and tested in the userform and object references set up ok.
I can't figure out how to link the indicator to the excel cell.
This is part of a larger project I am trying. Other control such as bargraphs, Switches etc. to be added if I can get the first one working.
Thanks in advance
You need to first add a reference to the Microsoft Excel x.x library in your control's references.
Next, you should add a private module level variable of type Excel.Worksheet, and declare it WithEvents, e.g.
Private WithEvents m_oWorksheet As Excel.Worksheet
You should also create a Property Set procedure called Worksheet which sets this variable.
Then you should add code for its Change event, e.g.
Private Sub m_oWorksheet_Change(ByVal Target As Range)
If Target.Column = 1 And Target.Row = 2 Then ' m_oWorksheet.Range("A2")
'Do some coding here
End If
End Sub
Obviously, .Column = 1 and .Row = 2 would be replaced by the cell coordinates you are interested in. I originally used coordinates like "A2", but found that the objects returned from m_oWorksheet.Range("A2") cannot be directly compared with the Target object, e.g.
If Target Is m_oWorksheet.Range("A2") Then
I tried to extract the cell reference "A2" from Target, but I can't seem to find a way to do it, unless you write a function to do the conversion of Column/Row to a string reference.
Note the previous answer I provided was very wrong, since I was testing
If Target = m_oWorksheet.Range("A2) Then
... which only worked because the default value properties were identical. This would fall over if any changed cell had the same value as a "watched" cell.

Creating a custom hyperlink function in excel

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.

Getting ComboBox Value In A Cell?

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.

Resources