last day (15 days later) » 

7:44 PM
1
A: IsInArray function error: Type Mismatch VBA

Scott CranerUse variant arrays: Sub sort() Dim rowNo As Integer Dim colNo As Integer Dim PIList() As Variant Dim GSList() As Variant Dim FilterList() As Variant Dim currCellCont As Long rowNo = 2 colNo = 2 PIList = Array(0, 1, 2, 3, 4, 5) GSList = Array(6, 7) FilterList = Array(89752, 89753, 89754, 89755,...

 
Again this ActiveSheet...
 
@JohnyL dude, if you can't see that you might be wrong when two of the top vba users disagree with you on this, there is no point arguing, so please keep your opinions to yourself. Do some research on who Mat's Mug is and what he does before you dismiss his knowledge. You might just learn something.
 
I guess, he's an expert on ActiveSheet theme) BTW, you didn't answer, why prefixing sheet is not enough...
 
I am not sure what you mean by prefixing sheets.
 
I mean, why prefixing with just "ActiveSheet" is not enough?
 
7:44 PM
You mean by leaving it blank and letting vbe assume the activesheet? Mat's Mug did answer that in his comment to you on the last string. Normally in this situation I would use With ActiveSheet or if the sheet was specific I would use With Worksheets("Sheet1") then I did not need to manually activate the sheet and could run the code from anywhere. Then just prefix the ranges with .. But in this specific case it was just me being lazy and using copy/paste to get the minimum amount of stability.
 
Hi, Scott! Are you here? :)
 
OK. I will explain what I mean.
 
<lurks>
 
Prefixing with ActiveSheet indeed clarifies the picture, but this is STILL not enough, becasue... well, because there can be several workbooks, which have THEIR OWN active sheet! So, prefixing with ActiveSheet, you effectively refer to active sheet of a workbook whichever happens to be ACTIVE. So, if to be MORE correct, then you must append ActiveSheet with Workbooks("MyWorkbook").
 
7:49 PM
if that means to be the workbook the code is written in, then you should use ThisWorbook instead
 
Yes, or ThisWorkbook, of course.
 
also in ~15 years of writing Excel VBA I've pretty much never needed to write a macro that works off any given whatever-is-active worksheet. there's always an assumption behind ActiveSheet.
 
Yes, and if the code were refering to multiple work books or even an outside workbook I would suggest they use ThisWorkbook to ensure the correct workbook is being referenced.
 
also ActiveSheet always refers to Application.ActiveSheet - there can only ever be only one, and it's always going to be in Application.ActiveWorkbook.
but yeah, Workbooks(n).ActiveSheet is legit
 
@Mat'sMug But you insisted that ActiveSheet must be the prefix, but I said, that if you want to be sure about which cells you're refering, you should also prefix with workbook reference. But even now you talk about assumption - and I, too, talked about assumption. And yes, for almost 12 years of my VBA, I didn't even remember that I needed the workbook reference. And even if I did, these were very rare cases.
 
7:56 PM
my stance is that Cells, Names, Range, Rows and Columns all implicitly refer to ActiveSheet when they're used in a non-worksheet module, and all implicitly refer to Me when they're used in a worksheet module, which makes identical code behave differently depending on where it's written in - hence, qualifying it with ActiveSheet makes it explicit, and work identically wherever it's written.
but robust code hardly ever works off ActiveSheet, explicitly or not
like that Sort method, that assumes the active sheet has a rather specific layout
it using ActiveSheet is a lie
it wants to work off Sheet12 or whatever - i.e. a specific worksheet in a specific workbook, with a specific layout
 
The very first thing I learned about sheet modules is that everything that's written there belongs only to that sheet.
 
I have a project with 86 classes, 25 worksheets, 11 user forms and 3 standard modules. Total worksheet code-behind: 0.
 
By the way, my hand book was and is "Excel 2007 Programmer's Reference". This is the splendid book I ever read )
 
most Excel/VBA books I've seen teach you how to write stupid macro-recorder type code
i.e. .Select and .Activate all over the place
 
This book is an exception. It's great book. I advise this book to anyone who wants to learn VBA - if, of course, they know English (I'm from Russia) :)
 
8:02 PM
once you've learned the basics of VBA, you should learn the basics of OOP and design patterns, to decouple your logic from the worksheets
funny, I'm just about to publish a blog article about exactly that
never seen any book mention anything about it either
 
This books just tells about the difference about Select and Activate - the whole chapter is devoted to it :)
That's why it is great :)
For instance, you will read there how to get array from Array function which will always have lower bound zero - no matter which Option Base you have :)
 
ah, here it is
in VBA Rubberducking on The Stack Exchange Network Chat, 35 secs ago, by Blogging Duck
posted on December 08, 2017 by Rubberduck VBA

Your VBA project is embedded in an Excel workbook. It references the VBA standard library; it references the library that exposes the host application’s (i.e. in this case, Excel’s) object model; it includes global-scope objects of types that are declared in these libraries – like Sheet1 (an Excel.Worksheet instance) and ThisWorkbook (an Excel.Workbook instance). These free, g

@JohnyL that's nice, but you shouldn't make assumptions about array lower bounds anyway - always iterate an array For i = LBound(theArray) To UBound(theArray) and the lower bound can be anything, nothing will break
(and whatever you do, never iterate an array with For Each)
 
@Mat'sMug In my office I am an Excel Master, but then I read your blogs and answers on code review and I feel like a bumbling idiot.
 
@ScottCraner I'm flattered... but I refuse any pedestal ;-)
(although, someone did nominate me for MVP recently)
 
If you use VBA.Array, your array will ALWAYS have zero lower bound
 
8:13 PM
Array is VBA.Array..
 
Heh... Just check :)
 
hey wait a sec
 
OK)
 
@Mat'sMug I was nominated once, did not happen, My guess with your background and blogs you have a better chance
 
@JohnyL Rubberduck resolves both VBA.Array and Array to VBA._HiddenModule.Array (variant-returning function)
from VBE7.DLL
are you saying unqualified honors Option Base while qualified with VBA doesn't?
 
8:18 PM
YES :)
 
dammit VBA
 
Heh)
 
no wonder nobody managed to make a decent VBA parser after all these years... everything is a tangled mess of bloody edge cases
@JohnyL tried Rubberduck yet?
 
@Mat'sMug I will read a bit later )
There's another quirk...
Say, you get some sheet's row.
Dim rngRow As Range
Set rngRow = Rows(10)
 
some sheet's indeed ;-)
 
8:24 PM
Here's quirk: you can't get 7-th cell by this code:
Dim rng7thCell As Range
Set rng7thCell = rngRow(7)
Try it )
 
IIRC both params are optional and the first one is named Row so you need rngRow(,7) to get a column
 
You're wrong... )
 
@ScottCraner ^ see
=)
 
yeah I created a quick code to test the Option Base 1 and am as flabbergasted as you @Mat'sMug
 
@JohnyL IDK man, I tend to avoid relative ranges, such code quickly gets confusing
 
8:28 PM
Sheets("Sheet1").Cells(26) is NOT 26-th row) - it's Z1 cell )
but we detoured a bit from my original question)
 
also .Cells(withOneParam) just looks wrong
 
@Mat'sMug There's nothing wrong there )
It's like counting from left to right, from top to down)
 
yes, look at intellisense. Cells wants RowIndex and ColIndex arguments: supplying both behaves intuitively, skipping one raises eyebrows
and by "relative ranges" I meant e.g. Sheet1.Range("B10:E25").Cells(thingsHereArePossiblyConfusing)
seeing such code rings "bad worksheet layout" in my mind
maybe it's just me though
 
@Mat'sMug unless you do not know the actual range but the relative range.
 
I like to never assume the actual range
i.e. abstract it behind a named range
let Excel deal with the cell addresses
 
8:33 PM
For ex you want the second column of the second row of the second area that is not hidden.
Not that that specifics will happen often, But I saw a question just the other day that was close to that.
 
code in most SO questions I'd scrap and rewrite if I encountered IRL :)
 
With SO wanting minimum details we can only answer what is provided, and at times we hold our nose and give them an answer without knowing the full picture. Code review has more leeway on getting more specifics.
 
8:46 PM
in VBA Rubberducking on The Stack Exchange Network Chat, 4 mins ago, by ThunderFrame
Option Explicit
Option Base 1

Sub test()

  Dim a As Variant
  Dim b As Variant
  Dim c As Variant
  Dim d As Variant

  a = Array(1, 2, 3)
  b = VBA.Array(1, 2, 3)
  c = [_HiddenModule].Array(1, 2, 3)
  d = VBA.[_HiddenModule].Array(1, 2, 3)

  Debug.Print LBound(a), LBound(b), LBound(c), LBound(d)

  'Prints 1 0 0 0

End Sub
That's nasty
So RD needs an inspection for unqualified Array calls
 
add it to the list of enhancements that I won't ever label
 
Hey, guys, if you're still here, here's what I want to add.
In general, any Range object is considered to be a "mini-sheet", i.e. all laws of referencing on sheet's cells are applied to Range object.
For instance:
Dim rng As Range
Set rng = Range("F3:H5")
MsgBox rng.Range("B2").Address(0, 0) 'Shows G4
 
@JohnyL yeah that's why a range of a range is confusing and why I avoid them like the plague. at least there's no OffSet calls sprinkled in there ;-)
 
@Mat'sMug Yep! That's why I try to avoid such kind of referencing when helping someone except when I need some short-cut :)
So, let's get back to my original question.
The Rows DO return Range object, but it behaves differently:
Dim rngRow As Range
Dim cell As Range
Set rngRow = Rows(7)
Set cell = rngRow(5) 'Incorrect :(
Set cell = rngRow.Cells(5) 'Correct!!
 
Work with variant arrays instead. Your code will be MUCH faster and you won't have to put up with these API quirks ;-)
 
9:02 PM
Here's one more quirk! Try this code - and you'll be surprised with answer:
Dim rng As Range
Set rng = Range("G1:H3")
MsgBox rng.Cells(8).Address(0,0)
Tip - note the location of this cell! :)
 
I don't need to try it to know the result will be off-putting. Anyone writing such code for production needs to go flip burgers.
 
Ha-ha! :)
 
=)
 
Just because it will do it does not mean we should. :)
 
Yes, no one in sanity will ever use such code, but it's welcome to know about these quirks )
Arrays are good choice, but:
1) transferring Range to array, we lose the offset
2) we have mere data, i.e. don't have access to cells' formatting
3) you can't easily expand the range (i.e. there's no Resize equivalent)
 
9:07 PM
in VBA Rubberducking on The Stack Exchange Network Chat, 4 mins ago, by ThunderFrame
Sub test()
  Clng 1 'Syntax error
  VBA.CLng 1 'runs just fine
  CDec 1 'Runs just fine
End Sub
 
Do you know that you can iterate over YOUR CUSTOM collection without calling magic Items member? :)
 
#TheresNoMagic
 
So, let's have we have Student class:
 
The Item property is merely a convention. It's a default member i.e. has VB_UserMemId attribute value 0
 
And did you know that your class can be public? :)
 
9:11 PM
The magic isn't there, it's with the NewEnum member which returns an IUnknown and has VB_UserMemId attribute value of -4
@JohnyL VB_Exposed module attribute
 
Yep... Very handy)
 
The more interesting one is VB_PredeclaredId
Combined with exposed, you can make factory methods and have truly immutable types
 
Frankly, never used it much) Had no chance to apply it :(
 
Abused though, you get half the userform questions on SO
 
Useful article - will take some time to read it ) Thanks)
 
9:16 PM
@JohnyL give it to your custom collection class and expose a Public Function Create(ParamArray values()) As WhateverThatClassIs
Then you can do e.g. Set items = List.Create(1,2,3)
 
I knew all these things but in reality had no chance to use them so eagerly... The class in its entirety is rarely used by people - they try to avoid this theme 'cause they think it's hard to grasp :(
Yes, those attributes do the trick. I will get the chance to try it )
As for "There's no worksheet". I barely understand why would one use interface for sheet's module?? Is it some kind of academic research? :)
 
@JohnyL because worksheets are data, and data access intertwined with code logic is terrible code in any language
 
You say about decoupling?
But...
 
Note that I'm on a personal vendetta to prove VBA just as OOP-capable as any other "real language" out there
 
VBA is OOP? Inheritance? Overloading? What about constructors? :)
 
9:27 PM
overloading and constructors have nothing to do with OOP
they're just language features
45
A: Is VBA an OOP language, and does it support polymorphism?

Mat's MugOOP is sitting on 4 "pillars": Abstraction - Abstracting logic and concepts can easily be done by defining objects in class modules. Strictly speaking, abstraction is also achieved by using meaningful identifiers and extracting procedural code into methods (class members). Encapsulation - Cla...

and inheritance is over-rated
 
They are HANDY features. Without overloaded constructor the one can forget to call magic INIT method (or Startup - whatever). With overloading we do not have such problems...
 
FWIW it's COM that doesn't nicely supports method overloading
 
Yes, that's why this very missing part...
 
and if your VBA classes are public, then they're not creatable - so you must have a factory method to create them
COM loves factories
and COM is absolutely object-oriented
and VBA is but a thin wrapper over COM
keep in mind that VB6/VBA was around well before .NET was a thing
the only thing that stands in the way of comfortably writing OOP code in VBA, is the IDE itself
enter Rubberduck
and now you can organize your classes in folders, navigate to implementations of interfaces, and so on
 
But... ordinary people don't have time/will to learn that deep...
IDE leaves much to be desired :)
At least, we have Locals window ))
 
9:33 PM
and a stack trace ...that isn't programmatically accessible
 
Yes... There was one case when stack trace helped me A LOT!
 
call stack, I should say
 
I understood ya)
 
ordinary people write shitty code...
...and then ask shitty questions on SO :-)
 
This is because they don't wish to learn it... In our forums there LOTS OF such people - 99% :)
 
9:35 PM
most Rubberduck inspections originated on SO, with the goal being "if that user had Rubberduck, they wouldn't have needed to ask this question"
 
<slowly raises hand> yup that's me
 
They just want ready answers... They even don't google their questions :(
 
:)
 
:)
 
@JohnyL I tend to hammer these as dupes
(although I haven't been very active in the last few weeks)
 
9:37 PM
But still there are people who even use classes. However, these were VERY rare questions... )
Also people ask about RibbonX - an interesting theme, too :)
But RibbonX is complicated... BTW, one flaw of this mechanism is that textBox raises event only after loosing focus - not when typing characters (
 
I switch over to VSTO/C# when I need to do Ribbon work
 
Also, when using dynamiControl, people double quotation marks while they forget that XML allows apostrophes :)
Dim xml As String
xml = "<student name=""Peter"" age=""25""/>"
when they could write more readably:
xml = "<student name='Peter' age='25'/>"
Nice! :)
 
@JohnyL would be nice if RD could statically determine that the string contains XML markup, and make that suggestion / offer a quickfix to replace all ""'s with ''s
or SQL. and warn about concatenated WHERE arguments and SQL injection...
 
Pardon, what is RD? :)
 
Rubberduck
 
9:46 PM
Ah)
 
Need to give it a try )
 
there's a number of known issues - don't load/unload the add-in from the VBE's add-ins manager
(unless you want to brick your VBE)
 
Ha-ha)
 
also the module/member attributes/annotations aren't going to work in 2.x - we currently have 2 parse trees per module, one with the attributes and the other from the VBE's code panes (for the correct in-editor token positions) ....problem is that when we rewrite the module (say after a quickfix or refactoring), we work off the codepane token stream, ...which means the attributes get wiped out.
once we get our own code pane (soon...ish), we won't have that problem
I want code folding, custom syntax highlighting, actually useful intellisense and autocomplete, ..you name it
a VBIDE running RD 3.x is hardly going to be recognizable
already the Code Explorer makes a huge difference
it legit replaces the VBE's Project Explorer
(we hijacked its hotkey!)
 
9:53 PM
Ha-ha) #getbackF2 :)
 
that's Ctrl+R
 
Oops) thought about Object Explorer))
 
refactor/rename is also a must
and refactor/extract-method is in progress
 
So, do you alone write this code? :)
 
hell no!
 
9:55 PM
:)
 
35 contributors and counting
I architected most of it
then folks joined and fixed my bugs
I can confidently say that we have the single most accurate open-source VBA parser out there
 
I see you use C#. Is it possible to use Roslyn to parse VBA code? It's a almost legit VB.NET code (except, for instance, SET keyword) :)
 
no
notably because of stupidities like the VBA.Array vs Array and VBA.CLng / CLng quirks, and other grammar oddities
 
It's a pity... (
But this would be cool idea :)
 
except Roslyn's parser isn't open-sourced
and one can't go and add a language to it
so Roslyn is a dead-end
 
9:59 PM
:(
 
we did not-so-bad with Antlr though
 
I see :)
using Antlr4.Runtime;
 
find me code that VBA can compile, that Rubberduck's parse chokes on
 
I will find it)
 
when you do make sure you open an issue on our repository!
confusing our resolver is a little bit easier though - but TBH if you have real production code that's ambiguous enough to mix up RD's resolver (aside from the handful known corner-cases), the fix is likely 10K volts through the keyboard
 
10:02 PM
Would it parse it? :)

Dim s As String
Dim ptr As Long
s = "Some string"
ptr = VBA.[_HiddenModule].StrPtr(s)
It's a legit VBA code)
 
(caret is on StrPtr)
 
It's just cool :)
 
the code explorer even displays docstrings
actually the RD toolbar does too
(we need to fix these \r\n)
 
A class? :)

Private col As New Collection

Property Get FileProperty(sPropName As String) As String
FileProperty = col(sPropName)
End Property
Oh... I have to go now :(
It's a deep night here)
It was pleasure to talk :)
 
anyway get Rubberduck - this is our "war room":

 VBA Rubberducking

This chat has moved to Discord: discord.gg/MYX9RECenJ
^ join anytime you want to chat
 
10:10 PM
Already there! Thanks :)
Now it's sleepy time :(
See ya :)
 

last day (15 days later) »