Excel VBA Custom Function giving "Reference Not Valid" Error - excel

I've attempted to track down and solve this error for hours now and I just can't figure it out. Here's the setup.
I have one excel workbook which has two sheets in it: "Input" and "Calculations". I've written in a few custom functions to calculate certain things. These functions are used in the "Calculations" sheet, but reference cells in the "Input" sheet. Now if I'm just using the sheet itself everything works perfectly fine and the functions work.
However, I have a second excel workbook which interacts with the first. I have a macro in the second workbook which attempts to define values in the "Input" sheet of the first workbook. However, when it does this, suddenly the functions don't work. When I attempt to trace the error of the cell in the "Calculations" sheet, and attempt to go to the cell in "Input" sheet, it claims the reference is invalid.
I have no idea what the problem is. At first I thought it maybe had something to do with the name of the first workbook (which was "Log K Calculator 7.0.0.xlsm") but I've tried changing that and I get the same problem. Here is the macro in the second sheet which attempts to change the values in the first:
Sub macro()
Dim logK As String
Dim this As String
logK = "Log K Calculator 7.0.0.xlsm"
this = ThisWorkbook.Name
Workbooks(logK).Activate
Workbooks(logK).Sheets("Input").Cells(11, 4).Value = Workbooks(this).Sheets(1).Cells(1, "B").Value
Workbooks(logK).Sheets("Input").Cells(12, 4).Value = Workbooks(this).Sheets(1).Cells(2, "B").Value
Workbooks(logK).Sheets("Input").Cells(14, 4).Value = Workbooks(this).Sheets(1).Cells(3, "B").Value
End Sub

I know this thread is 4 years old but, just in case anybody is still searching for the answer like I was, for me this error was caused not by my code but by the fact that I was running the procedure by clicking on a textbox which I had copied from another workbook. I had attached the procedure/macro to the textbox but had forgotten that there was already a hyperlink assigned to the same textbox. Removing the hyperlink fixed the issue.

You might want to check how Excel is treating whatever value is sitting in your external workbook. E.g. is it treating the numbers as text? You could check this by entering, say '10000, '300 and '600 manually in the input sheet (forcing it to treat them as text but display numbers), and see if you get the same ref error.
If you do, then casting the value into a typed variable (Long, Decimal, you name it) would probably fix the issue. Or at least make VBA choke on the incorrectly formatted ones (e.g. some have spaces in them, which might explain the apparent inconsistency)

Related

Excel VBA refer to worksheet that uses icon/emoji as part of name

I'm using Excel for Office 365 MSO 64-bit.
I want to write a VBA macro that selects different worksheets in a workbook based on the worksheet's name.
For example, I have two lines of VBA code that activate a workbook and then select a specific sheet in the workbook by the sheet's name.
Windows("myworkbook").Activate
Sheets("mysheet").Select
However, I have to work with some sheets that contain icons or emojis in them. For example, there is a worksheet that has this name: "đźš‘ Patient".
If I try to paste the icon/emoji into VBA like this: Sheets("đźš‘ Patient").Select, the icon does not show up in the VBA editor. Instead, I get Sheets("????? Patient").select.
I have also tried to use ChrW() to encode? the ambulance character (see here: https://www.compart.com/en/unicode/U+1F691)
When I run this macro below), I get an invalid procedure call or argument as noted below.
Sub SelectWeirdSheet()
Windows("MYWorkbook.xlsx").Activate
x = ChrW(128657) ' get invalid procedure call or argument here
Sheets(x & " Patient").Activate
End Sub
I also tried code for ambulance... also tried ChrW(&H1F691), but I get the same error.
My suspicion is that I am using the wrong argument for ChrW(), but I'm lost.
edit: So, the docs say that my argument for ChrW() is out of range. That helps explain the error, but I'm still missing a work-around.
Question: Is there a way to refer to use VBA to select worksheets that have an icon/emoji as part of their name?
I know you can also refer to worksheets by index number like this Sheets(3).Select.
However, there will be instances where I don't know the index of the sheet ahead of time, but I will know the name of the sheet, so it is preferable for me to call the worksheets by name.
Thank you.
In addition to the self-answered response, when working in a single workbook, the coder can assign a CodeName to the sheet in the VBA IDE, and then use that CodeName directly. This is really only valid if the Sheet is not re-created (i.e. is a permanent sheet in the book) at any stage, because a new/copied sheet will be automatically given a new CodeName by Excel.
For example, if given the CodeName shtPatient (see picture bellow), the code could be:
Sub SelectWeirdSheet()
' Windows("MYWorkbook.xlsx").Activate '<-- this approach has limitations
shtPatient.Activate ' See my comment below about the limitation - this will not work as expected in this example.
End Sub
Note: https://stackoverflow.com/a/10718179/9101981 explains why not to use Activate, but I have left the code as-is for the purposes of this answer. Also look at Using Worksheet CodeName and Avoiding .Select & .Activate. Another limitation noted is that the CodeName is only valid for the workbook that the code is in - so may not be applicable in this case.
I have highlighted the CodeName parts of the IDE in the image below, see how "Test Patient" is not called "Sheet7", but instead has a meaningful name that I gave it in the properties window below.
In order to properly address the emoji, it should be split into two separate unicode characters.
In this case, it would be x = ChrW(&HD83D) & ChrW(&HDE91)
Those two unicode characters make up the ambulance emoji.
So, this Macro now works.
Sub SelectWeirdSheet()
Windows("MYWorkbook.xlsx").Activate
x = ChrW(&HD83D) & ChrW(&HDE91)
Sheets(x & " Patient").Activate
End Sub
Found the solution on reddit of all places https://www.reddit.com/r/excel/comments/6pq1r1/vba_how_can_i_write_emojis_using_chrw/

Excel automatically changing to date format, even after correcting

I am helping to update someone else's VBA code since they got pulled to a different project. The code reads data from an input sheet, then unhides 4 results forms, populates them, saves them as a CSV file, then rehides them.
The issue: One of the data entries are numbers formatted as ##-#, like 20-2, 13-5, and 12-1. The 12-1 is the issue. Excel sees it and reads it as a date format and prints 1-Dec in my results sheet.
Solutions I've tried: I tried stopping the program before it rehides the data and changing the format but it throws off the numbers. And then I can't save it either, because the program has run halfway and I don't want to save the document like that. I then tried to unhide the sheets at the end after the program ran and cleared, but without completely removing the data after the program runs, it doesn't run correctly when you try to run it a second time. Lastly I tried unhiding before the program even ran and changed the format setting from "General" to "Text", but even after saving and closing it doesn't seem like that had an affect.
My Question: First of all am I changing the format right? And secondly does anyone know how to combat excel automatically formatting in this way. I have been working in VBA for about 3 weeks and have only encountered this once before but it fixed easily. This one doesn't seem to follow that pattern.
Since I was given an answer I thought I'd run my first self Q & A now, for those who may come upon this in the future. Credit to those users in the comments above for helping me figure this out. A code line like this:
Dim variable1 As Variant
variable1 = Sheets("Sheet 1").Range("A1").Value
Sheets("Sheet 2").Range("A1").NumberFormat = "#"
Sheets("Sheet 2").Range("A1") = variable1
Or with the cells option, we'd see code like this:
Dim variable1 As Variant
variable1 = Sheets("Sheet 1").Cells(1,1).Value
Sheets("Sheet 2").Cells(1,1).NumberFormat = "#"
Sheets("Sheet 2").Cells(1,1) = variable1
Both of these codes dimension a variable to store cell A1 in from Sheet 1, refer to sheet 2 and set that cell to a new format (making it format as a number as opposed to automatically formatting), then the last line sets that newly formatted cell equal to the value in the variable, but while retaining the new format we've set.

Macro to compare dates from different file

I am an old man trying to compare dates from two different files in Excel.
My code is:
Dim i As Integer
For i = 1 To 7
IF Data_for_Processing.xls (“SOLARLOG”). Cells (i,”A”).Value = Day_Conversion_chart.xls (Sheet1).Cells (i+2, “B”) Then
Cells(7+I, “B”)=”Equal”
Else: Cells(7+i, “B”) = “NotEQ”
End If
Next i
Will anyone help?
First of all, I would recommend following #simoco 's advice - Reading the documentation will provide the tools for solving future problems and give you the basics. As well as that, I would recommend using vba help. And another very useful tool for trying commands could be recording macros and analyzing them later on the editor.
So, first you need the code to be inside a macro. It will look like this (I chose the name TestMacro):
Sub TestMacro()
'Code here.
End sub
You should take into account that when your macro is running, it does so from the sheet you are working in, so any partial references to cells, etc. will refer to the book you are in and the sheet you are in when you run the macro. It is possible to select another sheet or book, and if you do so manually or on the code, references will be applied on that selected book or sheet.
What I call partial references here are those that read simply "ThisCell" instead of "ThisBook.ThisSheet.ThisCell". I would say that using partial references, though, is appropriate in a vast majority of cases.
The way your code is organized, be careful to run it from the workbook where you want the data to be in the end, let's say, in your 'main' workbook, so that the final values will be written there..
Another comment: whenever you want to use another file, this file must be open (as far as I know), while you are using it. In your code, you don't open any file, so the macro will not work if you don't open ALL referenced workbooks manually prior to running the macro.
When you want to reference something inside something, you mostly use ".". Please read the documentation - You will get a better idea of how this works. For this example:
Book.Sheet.Cell.Value is the structure you are using.
A book can be referenced as Workbooks("Name.xls") if it is open.
A sheet or worksheet can be referenced as Sheets("Name") or Worksheets("Name"), and also with numbers, like Sheets(1) or Worksheets(1). The differences can be seen on vba editor help. I chose Sheets(...) for your example.
Be careful with the symbols. I guess this was probably my problem, but I have to mention it just in case: When I copied your code, instead of double quotes (""), I got something different, that Excel would not recognize. If for any reason you are using different symbols, Excel might not understand.
A cell can be referenced in various ways too. The Range object is used extensively, and if you want to use "A1", "C44", etc., it's probably better to go for it. I like using Cells(,) as you did, when possible. As far as I know, this works nice with numbers (Cells(1,2), for example), which may be very convenient too. I kept this on your code, changing "A" and "B" and writing 1 and 2, respectively.
With all these changes incorporated:
Comments:
'NOTICE THAT ALL WORKBOOKS MUST BE OPEN.
'["A"] changed to [1]
'[Sheet1] changed to [1]
'["B"] changed to [2]
'Data_for_Processing.xls(“SOLARLOG”).Cells(i, 1).Value
'becomes Workbooks("Data_for_Processing.xls").Sheets(“SOLARLOG”).Cells(i,1).Value
'Day_Conversion_chart.xls(1).Cells(i + 2, 2).Value
'becomes Workbooks("Day_Conversion_chart.xls").Sheets(1).Cells(i+2,2).Value
'["B"] changed to [2]
And one possible solution:
Sub TestMacro()
Dim i As Integer
For i = 1 To 7
If Workbooks("Data_for_Processing.xls").Sheets("SOLARLOG").Cells(i, 1).Value _
= Workbooks("Day_Conversion_chart.xls").Sheets(1).Cells(i + 2, 2).Value Then
Cells(7 + i, 2) = "Equal"
Else: Cells(7 + i, 2) = "NotEQ"
End If
Next i
End Sub
This worked on my Excel example - I hope it is of some help.
Regards.

Freezing certain cells - VBA

I have a question about freezing certain cells. But first let me explain the situation.
I have made a search box in my excel sheet and when you search for a letter or word; the results show up in cells below the search box. Now I want to freeze those cells, so that wherever I go in my sheet. I can always use the search box and see the results.
The cells for the searchbox and results are B2:B25. Those are the ones I want to freeze. Also the only sheet I want to use this on is the sheet "Reading". On the rest of my sheets I do not use a search function.
So my question(s) is : Do I need to put the code inside a module or on that sheet, and how do I do this?
Now I have tried the following
Range(Cells(2,2), Cells(25, 2)).Select
ActiveWindow(or maybe Reading?).FreezePanes = True
Inside a module. But it did not work and I do not know what else to do.
Any help is much appreciated! Since I am very new to VBA.
Almost there. Problem is that the 'range' and 'cells' needs to be directed to the 'Reading' sheet, like so:
Sheets("Reading").Range(Sheets("Reading").Cells(2,2), Sheets("Reading").Cells(25, 2)).Select
ActiveWindow.FreezePanes = True
but if it always is B2->B25, why not use:
Sheets("Reading").Range("B2:B25").Select
ActiveWindow.FreezePanes = True
This should work. Select is not very desirable, because it is very slow, but in this case, you need to (as far as I know).
EDIT
BTW, you can do this from within a code module or from within a sheet, but if you choose to do it from within a sheet, you cannot select another sheet. So just use the range.
EDIT 2
whoopsy, typo corrected. 'Sheet' should have been 'Sheets'

Simple vba program in Excel

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

Resources