Need to Update External References in an Excel Sheet while a Macro is Running - vba

I have an excel macro that sets Cells to an external location.
Range(NamedReference) = "='http://webaddress/ExcelSheet.xlsx'!NamedReference
Other cells use that location to calculate new values.
"A1" = NamedReference + 1
The problem is that I need to read the new calculated values back into the macro to export data, but the external link has not yet been calculated to any value. It is a #NAME? until the macro is done running. Is there any way to force excel to get those values during the macro run time?
I have tried a variety of things including
Calculate
CalculateFull
Any help would be appreciated. My current solution is to just close the macro on error and have the user re run the macro, but it is really kludgey.
**Edit: Forgot equals sign in formula

You could try
ActiveWorkbook.UpdateLink Name:=ActiveWorkbook.LinkSources
See on MSDN

Related

How to find active cells range in excel VBA

I am trying to open multiple webpage tab from my selected cells. I would like to find the selected cell (based on the mouse) starting and ending row and column information for further use of vba macro.
Thanks in advance...
You can do this:
x = ActiveCell.Address
MsgBox (x)
but really, you should try to avoid using selection where possible. The reason for this is because users can (and I've found, will) click in to other spreadsheets as the code is running and so what you have intended as the selection, may no longer be the actual selection. It also affects the longevity of the code because it's much more difficult to fix if something breaks.

Error 1004 when using =AND(ISERROR) formula in macro

I'm recording a macro to automate some Excel reports and have encountered the following bug whenever I try and run an iserror(search) formula:
Run-time error '1004': Application-defined or object-defined error
I have two lists. The formula iterates through the first list and compares the values with those of the second list, hiding any matching values.
The formula in Excel is like this only with a wider criteria range:
=AND(ISERROR(SEARCH($B$3212,B2)),ISERROR(SEARCH($B$3213,B2)))
It works perfectly when I insert the formula directly into the spreadsheet cell however I get an error when I record and later run the macro using the same formula.
EDIT 2
I got the formula insertion to work through the macro but now I cannot filter the data as before, even when I do it manually without the macro.
Below is a link to a picture giving an example of the type of lookup I'm trying to achieve, previously it worked perfectly and removed all the rows which contained a string from the 'to remove list' now I cannot get it to filter at all. I've tried removing the macro after saving in notepad in case the file had become corrupted but it still does not filter as before. What could be causing this?
This is how the lookup works
Cell [A13] would contain the aforementioned ISERROR formula in this example.
This formula doesn't translate well to VBA in its current form. You should use the VBA Instr function instead of the worksheet function Search.
Function FindSubstring() As Boolean
Dim rngFindText As Range
Dim rngWithinText As Range
Set rngFindText = Sheet1.Range("B3212")
Set rngWithinText = Sheet1.Range("B2")
FindSubstring = InStr(rngWithinText, rngFindText)
End Function
Sub foobar()
Debug.Print FindSubstring
End Sub
You are asking Excel a question to tell you to find the contents of $B$3212 in B2 and to find if again.
Usually the SEARCH is used to find the contents of one thing in another, by using it again the AND statement you are asking it again ... and for what?
Hence the question does not make sense.
What I think you might be asking if just once and if there is an error meaning it did not find it there in this instance for it to return 0.
=IF(ISERROR(SEARCH($B$3212,B2)),0,SEARCH($B$3212,B2))
I figured this one out, the original 1004 error was caused by vba only partially recording the formula, the solution involved simply going into the debugger to find which line hadn't been translated correctly and editing that line. I then had to edit the formula so as to be able to filter out values acording to my criteria and ended up with a formula closer to this:
=AND(ISERROR(SEARCH("Value1",B2)), ISERROR(SEARCH("Value2",B2)))

Blank Fields Copied as #N/A

I am working with an Excel 2003 VBA script that copies the content from worksheets in an external Excel file to worksheets in our own:
ThisWorkbook.Sheets(strTarget).UsedRange.Value = Workbooks(strFile).Sheets(strSource).UsedRange.Value
In a large number of blank cells, this function is posting #N/A instead of the blank values, which causes errors further down in the VBA code. This only occurs on some sheets, while others copy over just fine, sometimes by adding these values in extra rows and other times in extra columns. I have attempted to clear the error with IsNA to no avail:
If (IsNA(Workbooks(strFile).Sheets(strSource).UsedRange.Value)) Then
ThisWorkbook.Sheets(strTarget).UsedRange.Value = ""
Else: ThisWorkbook.Sheets(strTarget).UsedRange.Value = Workbooks(strFile).Sheets(strSource).UsedRange.Value
Is there a simple way to remove these #N/A values during the copy or even clear them after the fact?
Any other advise on how to handle this issue would also be greatly appreicated, as I'm not a VBA dev myself, but simply the lucky soul who got to pick this up when the only person with Excel and VBA experience left our team. Thanks in advance!
The problem comes when the ranges aren't the same size. You should resize appropriately:
With Workbooks(strFile).Sheets(strSource).UsedRange
ThisWorkbook.Sheets(strTarget).UsedRange.Resize(.Rows.count, .Columns.count).Value = .Value
End With
It's probably safer to clear the target sheet first using:
ThisWorkbook.Sheets(strTarget).UsedRange.ClearContents

Excel VBA: Resetting spreadsheet count

I have a excel VBA macro that dynamically generates and deletes spreadsheets based on user input. However, when I open the VBA IDE, it seems that although I am naming my spreadsheets in the subs that create/delete them, the overall count is still increasing.
For example, depending on how far into execution my program is, under the "Microsoft Excel Objects" folder in my current project, the spreadsheets in the current workbook could look something like
Sheet101(Sheet3)
Sheet103(Sheet2)
Sheet104(Sheet1)
Or
Sheet81(Inputs)
Sheet83(Date Adjustment Interpolation)
Sheet84(Pricing)
Sheet85(Comparison)
No matter if I delete the rest of them and add one, it still picks up where the last highest one left off.
I don't know how many times this macro will be run and I'd feel a lot better about putting it out there if I could reset this annoying tally on the number of spreadsheets that have ever been generated, since I don't know for sure where excel will cut me off. Plus it's just annoying.
My Question:
I would like to know how to alter that spreadsheet number, or at least what the relevant object is for doing so.
Thanks!
Thanks to #dijkay s suggestion on code names, I've found some code to accomplish this.
ThisWorkbook.VBProject.VBComponents("Sheet1").name = "test"
Will change the code name of Sheet1 to test, so in the Excel Objects folder, it will appear as test(Sheet1) for example.
This option, however, requires messing around with some trust/security settings in each individual excel client running the macro, which is unsuitable for my purposes, unfortunately. You can also change the value manually by changing the (Name) property directly in the IDE through the properties window.
here are some ideas you can try...
Sheets(x).Name = "Sheet" & x
or (assuming in this example, 'Sheet3' doesn't already exist:
Set Sheet3 = sheets.Add
Sheet3.name = "Sheet3"
This is more cleanup than re-setting
cheers,
Micéal

Apache POI and SUMPRODUCT formula evaluation

I have a template XLS file that I load with Apache POI and write loads of data in it, then save it as another file.
I have formulas in my XLS file like this:
=SUMPRODUCT((DS!B:B="IN_THIS_ONLY")*(DS!D:D="New trade"))
also tried
=SUMPRODUCT(0+(DS!B:B="IN_THIS_ONLY"),0+(DS!D:D="New trade"))
these evaluate correctly if I press Enter on the cell in Excel.
However, simply calling
HSSFFormulaEvaluator.evaluateAllFormulaCells(workbook);
does not seem to evaluate them, neither does pressing on the "Calculate now" button in Excel - so I guess this is a special formula or function.
The other, more conventional COUNTIFs and SUMIFs work fine, however these do not allow multiple conditions to be specified.
POI does not support array formulas.
Is there any way to make these work. I'm using POI version 3.7.
One can press CTRL-ALT-F9 to manually re-evaluate all formulas forcefully in Excel.
And here is the trick to make it work automatically on workbook open.
Add the following to your formula:
+(NOW()*0)
so for example, my SUMPRODUCT above becomes
=SUMPRODUCT((DS!B:B="IN_THIS_ONLY")*(DS!D:D="New trade"))+(NOW()*0)
And this works! Excel now recalculates my special formula cells on open.
The reason for this is that NOW() is a volatile function. Here is where I learned about this: http://msdn.microsoft.com/en-us/library/bb687891.aspx
Application.CalculateFull also works, but only in Excel 2007 and later (and of course, one must enable macros to run). Unfortunately, in my case even though I use Excel 2007 my workbook will be opened by Excel 2003 users as well, so this was not an option.
Is SumProduct an array based formula function?
If so, that would explain the issue. One option is to contribute a patch to POI to add the missing support. There's been some discussion on the dev list and bugzilla on what's needed, and if you were to post to the dev list then we'd be happy to help you get started.
Otherwise, you could just set the formula recalculation flag and get Excel to recalculate the value on load