Macro to compare dates from different file - excel

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.

Related

Excel VBA - WorksheetFunction.CountA error - Object required

folks. I'm a programming newbie, trying to write a macro to extract some rows of data from multiple workbooks and compile them into a new workbook, then graph them. I have figured out how to loop through the source spreadsheets, and a few other things, but right now I'm stuck on a couple of places. (I'll ask my different questions in different threads for clarity.)
This question is about an error when using WorksheetFunction.CountA to get the number of a list of items I'm searching for. I want to know the number so that I can know when I have found all of my search strings. If I can't find them all, I want to inform the user and quit.
Following advice on this question, I wrote a snippet to test the CountA function. I get an "object required" error. I have reviewed several threads on that topic, but I'm still not getting it. Here is my code snippet:
Sub a_test_kpi_count()
Dim kpi_list_count As Integer
Set kpi_list_count = Application.WorksheetFunction.CountA("kpi_list")
MsgBox "There are " & kpi_list_count & "kpis in the list."
End Sub
When I run the code, the editor stops with either "kpi_list_count" OR "CountA" highlighted. Well, THAT'S helpful!
I should add that "kpi_list" is a named range on the worksheet where the macro lives. However, I get the same error when I specify the range in this manner:
Set kpi_list_count = Application.WorksheetFunction.CountA("K3:K7")
Ergo, I don't think the named range is my problem.
A nudge in the right direction would be much appreciated!
OR, feel free to call me an idiot and point out my obvious error! ;-)
EDIT:
Thanks, Ben.
This code is working:
Sub a_test_KPI_count()
Dim KPIListCount As Long
KPIListCount = WorksheetFunction.CountA(Sheet1.Range("KPI_list"))
MsgBox "There are " & KPIListCount & "KPIs in the list."
End Sub
Thank you! Oddly, it does NOT work when I use the sheet name, buttons. Are sheet names case sensitive? I ask because the editor insists on "Buttons" rather than, "buttons".
A couple more questions for my learning, if I may, about some of your tips:
3, long vs. integer. In this case, I'm counting a short list (<6) items. Is integer acceptable here, or would it be best practice to stick with Long?
Camelcase vs snakecase. Noted. Is this simply a preference of more experienced programmers? Or is there a functional difference?
Your answers have all been of the kind I hope for. A fishing lesson, rather than a fish! Thank you!
Set is for Object variables - remove it.
You need a Range call when specifying a named range.
kpi_list_count = Application.WorksheetFunction.CountA(Range("kpi_list"))
99.9999% of the time you want a Long, not an Integer; see this question:
Dim kpi_list_count as Long
Best practice is to specify which sheet the Range is on (change as necessary):
kpi_list_count = Application.WorksheetFunction.CountA(Sheet1.Range("kpi_list"))
You can drop the Application if you want.
Consider using camelCase instead of snake_case.

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/

vba Userform macro edits wrong sheet

I have a userform that is supposed to insert a row on Sheet3 and populate some cells in that row with some values. it works great as long as I have sheet3 displayed. (The form is shown modeless to give me access to the sheets).
Anyway, I happened to have another sheet active and ran it again and was surprised to see it inserted the row not in sheet3, but in the one I had displayed... (Thank God I saved first!)
In the code, I specified a range object as follows to find the insertion point: (I'll truncate the code a bit to keep it simple)
Dim RecordRange As Range
Set RecordRange = Sheet3.Cells(RowVariable,ColumnVariable)
RecordRange.Offset(1,0).EntireRow.Insert
blah blah blah.
A workaround is to activate the sheet first:
Sheet3.Activate
That at least inserts into the correct sheet, but I'd rather not have sheet3 be displayed when I add the record, so I even surrounded that line with:
Application.ScreenUpdating = False
Sheet3.Activate
Application.ScreenUpdating = True
unfortunately, ScreenUpdating doesn't work from within a Userform Code module, so that bites...
I still don't understand why it chooses to insert the row into whatever sheet is active, when I've already specified sheet3 in the code. I have another Macro very similar that doesn't have this problem.
any ideas?
...so you figure your workaround needs a workaround? Hmm... I think that qualifies as a double-negative since a workaround is supposed to, by definition, fix problems rather than cause them...
A workaround is a bypass of a recognized problem in a system. A
workaround is typically a temporary fix that implies that a genuine
solution to the problem is needed. But workarounds are frequently as
creative as true solutions, involving outside the box thinking in
their creation.
Typically they are considered brittle in that they will not respond
well to further pressure from a system beyond the original design. In
implementing a workaround it is important to flag the change so as to
later implement a proper solution.
Placing pressure on a workaround may result in later system failures.
For example, in computer programming workarounds are often used to
address a problem or anti-pattern in a library, such as an incorrect
return value. When the library is changed, the workaround may break
the overall program functionality, effectively becoming an
anti-pattern, since it may expect the older, wrong behaviour from the
library. (Wikipedia)
Just sayin'... :-)
So instead of fixing the workaround, your original issue is (thankfully) straightforward.
You're using Sheet3 as an object, and I suspect you haven't assigned anything (like Worksheets("Sheet3") to an object called Sheet3.
Try this instead:
Dim RecordRange As Range
Set RecordRange = Worksheets("Sheet3").Cells(RowVariable,ColumnVariable)
RecordRange.Offset(1,0).EntireRow.Insert
If you indeed intended to use Sheet3 as an object then make sure it's declared as set, so for example you could instead use:
Dim RecordRange As Range
Dim Sheet3 As Worksheet
Set Sheet3 = Worksheets("Sheet3")
Set RecordRange = Sheet3.Cells(RowVariable,ColumnVariable)
RecordRange.Offset(1, 0).EntireRow.Insert
Also, just to point out: If either of these solves your issue then the problem would've "made itself known", by including one line at the top of every module (at least during development & troubleshooting):
Option Explicit
This link has a short explanation, but basically it forces you to properly declare all variables (thus helping to prevent future workarounds!)

Concatenating in VBA within Excel

I am trying to accomplish something apparently simple but not for me. I’m new to all this and I would like to see if I can get any far with this first project. Basically I have, say 3 text boxes with a string in it (name) and a button next to them. Then there is another text box which will hold all 3 names so that I could copy as one string into clipboard. Many tutorials out there refer to concatenating the strings however I’m still unable to find a decent answer. To be fully honest I am trying to achieve this task in VBA from within Excel 2010. So, my 3 names are actually in 3 different cells… Next to each of them I have a button with a macro attached (but vb will also be good for me) that will add the name into another cell. The buttons works ok but my problem is that I can’t get them to concatenate in Excel. Every button just overwrites what’s was there before. Any help? Suggestion? Tips? Mind you I can only be able to follow if the answer is simple and well explained as I am new to all of this. Thank you.
If you had 3 strings in A1, B1 and C1, you could get the concatenated string in D1 by putting in the formula `=CONCATENATE(A1,B1,C1)' in the cell D1. If you want to do it in VBA,
Public Sub MyConcatenation()
With ThisWorkbook.Worksheets(1)
.Cells(1, 4).Value = .Cells(1, 1).Value & .Cells(1, 2).Value & .Cells(1, 3).Value
End With
End Sub
If you won't take offense: You need to pick up an introductory book or website to learn VBA (it is not VB or VB.Net). It will be a long, uphill struggle to learn it through asking questions on forums.

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