Using a variable in a formula in Excel VBA - excel

I am having a problem with a piece of code that I’m writing. I have created a “parent” workbook which will be used by multiple users as the basis for some basic reporting. This workbook creates a number of child workbooks by VBA. The end users then enter values in these child workbooks, which are aggregated in the parent workbook.
However, I am having trouble with using a variable in a formula. If I use a formula such as (eg)
ActiveCell.Formula = “=S:\ThisIs\AnExample\FilePath\Name.xlsx”
then the formula works fine. However, what I need to do is change the path so that “Name” in the example above is actually a variable (fname, which is a global [string] variable).
I thought something like
ActiveCell.Formula = “=S:\ThisIs\AnExample\FilePath\”& fname&”.xlsx”
(with a few brackets in relevant places) would do the trick, as that’s what seems to recommended in the responses I’ve seen to similar questions – but I’ve tried all sorts of permutations of bracketing of the above, none of which will do what I want.

To be on the safe side you could declare "Dim fname As String" and double-check the fname to make sure it is stripped from extension and generally trimmed correctly.

I'd say using a hardcoded path instead of a mapped path would be more reliable, if that is an option. It would prevent issues that would occur if a logon script failed to map the same drive letter to the specific network path the resource is stored in.

Related

Automatically name a file based on cell data and function when saving a spreadsheet

I have an .xltm template spreadsheet that I'm wondering if I can get a macro to populate the "save as" file name based on cell data, is this possible?
There are over 7 people who will have this spreadsheet, it's more of a form, and we are trying to figure out a way to keep the filenames uniform. I know there is the ThisWorkbook.BeforeSave, but I'm not really having any luck there. I just need it to make a file named something like $A$1 R $B$1 T $B$3.xlsx
how ever the problem im having is that one of the celss will have a function "Today()" and sometimes it will be a regular text the picture I included is off code that doeas work but only if the cell have a regular text in them but not a function, I quess it is due to it being a string or variable or something.
enter image description here
Any ideas on how to do this? anything helps thank very much.
I see from the image that you are working with Mac OS. The thing that comes to mind immediately is that the forward-slash character (/) is not allowed in a file name in Mac OS and by default, TODAY() is going to include the forward-slash character. Try using the replace function to switch it out for an underscore (_). So if your cell B7 uses the TODAY() function replace it with:
replace(range("B7").value,"/","_")
It also seems a bit strange to save an .xltm template as .xls file. Be sure you understand the workbook.saveas method including the fileformat argument
I think that part of your code should be:
ActiveWorkbook.saveAs strPath, xlExcel8

VBA ListObject inconsistent naming rules when using a macro (puts underscores at endings)

You can name your table "my000" but you can't name it "my001". You also can't name it "bab002", "lal0101" or anything similar.
When using macros to create and rename tables I noticed that sometimes it puts underscore at the end of the table name (like myt001) with no valid reason. Excel prompts that a name should not be in conflict with existing name, start with number or include space or not allowed character. The names that I try seem completely correct, by Excel changes them to for instance to "my001_", disrupting other parts of my spreadsheet.
To reproduce: open blank Excel, create an empty table with Insert -> table then try to name it "ba001" or something similar. When trying to do the same with vba, it puts underscore at the end ("ba001_"), having no reason to do this.
I expect vba to give the (supposedly) correct names to ListObjects. Instead it puts underscores at the endings in unexpected situations.
The conclusion based on what Mikku & Maeaex1 said, the table name is named in a convention that makes vba reference a cell "BAB001" due to ignoring the "00" within the name string.
Solution: change naming convention that is not consistent with Excel's cell naming convention, such as starting the table name string with an underscore " _ " which will also give the added benefit of when you reference it within excel when you start and type "=_" a list of all your tables and named range will appear instead of other functions that start with the same letters.

Excel dynamic ranges from Access code and Formula separators

I am currently rewriting some old Access code that defined named ranges in an excel workbook.
The old code is as follow:
oWorkbook.Names.Add "NameOfRange", "='Sheet1'!$A$1:$L2000"
With oWorkbook a Workbook opened from Access.
Since the range (number of rows) can change, I planned to use dynamic named ranges using Offset and CountA functions, and wrote the following code to replace the previous one:
oWorkbook.Names.Add "NameOfRange", "=OFFSET('Sheet1'!$A$1,0,0,COUNTA('Sheet1'!$A:$A),12)"
but then excel send an error 1004 There is a problem with this formula.
The same line of code executed from an Excel workbook works fine, and give the expected result.
On my computer, I use mixed English/French international settings, and my Office 2016 is in English, so I have a ListSeparator as ;.
When replacing the , by ;, the new formula below works:
oWorkbook.Names.Add "NameOfRange", "=OFFSET('Sheet1'!$A$1;0;0;COUNTA('Sheet1'!$A:$A);12)"
but I need my function to work on every configuration, not on only French/English bizaroid settings.
I tried to specify the named arguments (Name:= ... and RefersTo:=...) but its not correcting the problem. When called from Access, the code still need local separators (and maybe local function names? no idea).
So I can retrieve the computer excel List Separator (Using oWorkbook.Application.International(xlListSeparator) and replace all , in the formula with it, but maybe I am doing something wrongly and there is a better way to do?

Indirect not working

I want to reference an external workbook that is open. If I type =path\[file] directly into the cell (even though I am still asked to 'Update Values',) I am able to get the data I require. However, I am using INDIRECT because the name of the file changes everyday (date). So, I am using CONCATENATE to create a filename daily and then using INDIRECT to the cell where the concatenated formulas is. If you paste values to see what is being generated formula, it is exactly the same formula as above, =path\[file]. However, I continue to only get #REF! error.
I read through this, https://support.office.com/en-us/article/control-when-external-references-links-are-updated-87861952-ca9d-4d2a-a986-4d672c908d0d, and I still can not figure it out. I had it working on my computer at home last night but today and work it is giving me trouble.
To clarify, the formula that I am trying to get to work looks like this =INDIRECT("'"&CONCATENATE($F$129,$F$130,F95)) which worked yesterday at home. Can someone lead me in the right direction?
EDIT:
I have tried two options, =INDIRECT(F121) and =INDIRECT("'"&F121). The contents of F121 have been =CONCATENATE("'",F191,F192,F157) and =CONCATENATE(F191,F192,F157), respectively. I have also tried =CONCATENATE("'",F191,F192,F157) in the destination cell. F191 = [Liquidity Risk Dashboard v2.03 -, F192 = =TEXT(E3,"yyyymmdd")&"]", and F157 = Calculations'!D122. If I write ='[BMI Liquidity Risk Dashboard v2.03 - 20170105]Calculations'!D122 am asked to update values but, 100% have both workbooks upon in same instance
If I understand what you really have in your cells, the problem is that you are not properly naming the source workbook.
Try changing
F192: =TEXT(E3,"yyyymmdd")&".xlsb]"
Replace .xlsb with whatever the file extension really is for your file. (eg: .xlsx, .xlsm, .xls)

Excel Chart: Title & Axis Tiles based on named range

I thought this should work, but at times Excel has a tendency to make simple things complicated (or impossible).
I'm setting up a bunch of graphs. Because I anticipate I will have to translate labels at some point, I want to use named ranges for all my labels (then'll offset it for translation). There's VBA involved for other stuff already, so I kinda like to use name manager as much as possible. I think it makes things easier to maintain as well.
The problem arises when I try to set the Axis Titles, and the chart Title, as a reference to a cell that is a named range. I know I can set the reference to a CELL, by doing so entering in the formula bar while having the title selected something like:
=worksheetname!$A$1
However, let's say that my that cell is named graphlabel_waterpointY. I would like to do something like:
=graphlabel_waterpointY
Which fails. Upon diggin a bit, I found that I need to put the workbook's name before I can use the named range as such, like so:
=WORKBOOKNAME.XLSM!graphlabel_waterpointY
That works, however, I don't want the user to rename the workbook and later find that all the graphs titles show !VALUE instead of proper titles. Therefore I want some sort of flexible reference for the name of the workbook as well. I don't want to use:
=CELL("filename",A1)
& isolate the string there, because if the user has another workbook open that can fail as well. So I thought "well, since I'm already using VBA, I'll just set the workbook name in a cell upon workbook opening & have my formula for the titles reference it".
However, that fails as well. Even something like:
=META!$A$1!graphlabel_waterpointY
(assuming META!$A$1 contains the workbookname) will fail as well.
It seems dumb to me that I would have to hard-code the values. I'm aiming to have something translatable later on. Of course one can just do different version, but then it sucks to have to maintain 2 workbooks. Or I could settle for hard-coding the workbook names & have it said they can't change it. But that sucks as well.
==================
My solution as this point is the first mentioned, e.g. even if the cell has a named range, refer to it by its A1-style reference. Works but then I lose flexibility in the layout..... Maybe I'm being picky....

Resources