Value in a cell from CellReference in C# - excel

I am using Office Excel VSTO. I have a cell reference info of a cell in my workbook. say, Sheet1!$A$5. I want to get the information in this cell and its type. Is this possible in VSTO by any means?
I am now breaking this cell reference going to the sheet and cell get getting the values. I suppose more easy ways are possible.

I am not sure if this is what you are after, but the following gives you direct access to the cell:
var range = (Range)Globals.ThisAddIn.Application.Range["Sheet1!$a$5"];
var cellContent = range.Value2;

Ok I think I have your question figured out.
You want to use VSTO to replace a workbook link that you are using to update a value in your current workbook.
For me the clues are ....
1. want to get the information in this cell and its type
2. use VSTO to do it
3. am now breaking this cell reference
btw if my assumption above is correct, then please edit your question to make more sense for future readers.
Code Sample
//get workbook link cell ref
var range = (Range)Globals.ThisAddIn.Application.Range["Sheet1!$a$5"];
//determine type
// if straight linking a value this step is unnecessary unless using the type info to format the cell
// or because you are doing a transformation or aggregation on the data prior to putting it somewhere.
// if needed... do some try/catchs on casting it to oledate, bool, double, string in that order.
// get value
var value = range.Value2;
// update "active" sheet
var sht = (Excel.WorkSheet)Globals.ThisAddIn.Application.ActiveSheet;
sht.Range["A1"].Value2 = value;
// don't forget to call FinalReleaseCOMObject and GC.WaitForPendingFinalizers/GC.Collect block!!
Also note that yes, you will be "breaking the cell reference" if you use code INSTEAD. Note you could keep the workbook link, but then there's no point in using the code approach. My advice would be in general use code since it is more flexible, but take advantage of links when you want speed (of configuration) and the data doesn't require more than basic manipulation (SUM, IF, basic math operators).

Related

Creating a Dynamic Range that works for Excel to Save Name Ranges to a Static Web Page

I have a excel document that has several name ranges that are currently save to static web pages. I have recently tried to conver them to dynamic ranges, and have learned the dynamic named ranges work great within the context of the excel sheet itself, but fail once excel tries to save them as the static web page.
For example, I have a range
YardTabletLists!$EC$1:$EE$101
sometimes the content is exceeds the bounds or I have empty rows on my webpage.
the dynamic alternative is
=OFFSET(YardTabletLists!$EC$1,0,0,COUNTA(YardTabletLists!$EC$1:$EC$10000)+1,3)
If i refernce this name range anywhere within the sheet, it works, but when AutoPublish does it thing, I get the following error.
Error Notice
I was thinking of trying to conver the Dynamic range back to a static range somehow, and then direct the name rage to that Cell.... i.e.
Name range is directed to =E4, and E4 contains YardTabletLists!$EC$1:$EE$101, but I get the feeling that will give me the same issue.
Thanks to those who read this.
Not familiar with static webpage feature.
But possible to define and use “table” instead of “named range”?
With “table” Excel internally handles the correct range whenever the table size is modified.
Seems the static webpage feature supports also “filtered ranges”. Could this be a work-around, e.g. to filter out blank lines (while using max line number as static range)?
Indirect references (your example with E4) are a little tricky in Excel. I only used it once to define a list for a dropdown.
Muss be supported by the feature and requires “special” syntax
Update:
I have found some examples for VBA updating name ranges, and one excellent example that appears to answer the question:
https://excelchamps.com/vba/named-range/#Resizing_a_Named_Range_using_VBA_Dynamic_Named_Range
Sub vba_named_range()
Dim iRow As Long
Dim iColumn As Long
iRow = ActiveSheet.Range("A1").End(xlDown).Row
iColumn = ActiveSheet.Range("A1").End(xlToRight).Column
ActiveSheet.Range("myRange") _
.Resize(iRow, iColumn).Name = "myRange"
End Sub
for some reason the program hangs up at
ActiveSheet.Range("myRange") _
.Resize(iRow, iColumn).Name = "myRange"
does anyone see perhaps a syntax error I am missing?
Thank you :)

My Excel workbook with custom formulas breaks when I use other workbooks simultaneously

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.

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

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.

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.

Excel VBA split data in a cell and copy it to another worksheet

I'm very new to VBA and I'm stuck with a problem that probably has an easy solution.
In Cell A1 I have a string "UP 5487441 - some more text". I'd need to get only "OUP5487441" (yes without the space and text) to another worksheet into cell C3.
I have digged around a lot to find a solution for this but I only keep finding functions but I need it to be a part of a bigger VBA macro that's to be used for several files. But the data is always in cell A1.
If anyone has any tips I'm very thankful!
Greets
Sanved
This should work:
Dim splitValues() as String
splitValues = Split(ActiveSheet.Cells(1,1).Value)
Sheet2.Cells(3,3).Value = splitValues(0) & splitValues(1)
Obviously, you can make this considerably more robust when you add it to your existing code, but this is the general strategy to use.

Resources