Being relatively new to VBA and on the back of advice I've been given on this site, I'm trying to get in the habit of specifying data types when I code. I've been looking at the data types listed on the following webpage and thought about the scenarios in which each data type might be used:
https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/data-type-summary
However, I have a question about how Byte
might be used. In which scenarios would it be preferable to use Byte
over other data types? In other words: When would a 0 -255 data range be advantageous?
I'm not getting too caught up in data types but definitely curious about this one!
For most casual things, you don't need a Byte
data type - even if the values you intend to use are within Byte
range.
You don't typicaly need a 16-bit Integer
either for that matter - whenever you need an integer type in VBA, a Long
(32-bit, signed integer) is ideal, and consuming more bytes than you really need isn't a concern when available memory is measured in Gigabytes... which wasn't exactly the case in 1993.
Rule of thumb, if you need an integer type, use a Long
; modern processors are optimized for working with 32-bit integers, and internally there's no difference whatsoever, so using Byte
for values that fit 8-bit integers, Integer
for values that fit a 16-bit integer, and Long
for values that fit a 32-bit integer, ...is really just useless additional work that isn't saving any memory.
Byte
is a low-level data type very often used with arrays, that is useful for things like dealing with string encodings, for example.
Some standard library functions work better with Byte
values; VBA.Information.RGB
comes to mind:
While the function is happy to work with any Integer
, any argument value greater than 255 will cap at 255, so RGB(1000, 0, 0)
outputs 255
: feeding it with Byte
values kind of makes sense then, but only for self-documentation purposes - nothing to do with memory consumption.
VBA isn't dedicated to Excel. Think about Access (to stay within Office tools).
When you plan to store a million rows in a table, you might want to use a Byte
for some fields. You can then read your Byte
field into a Byte
variable.
As @Matthieu said, for Excel it has little value.
Keep in mind also that And
and Or
are bitwise operations in VBA. I already used Byte
+ bitwise operators to check for permissions, for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With