Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under what circumstances would VBA data type "Byte" be useful?

Tags:

excel

binary

vba

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!

like image 542
wgmcgowan Avatar asked May 14 '19 17:05

wgmcgowan


2 Answers

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:

Function RGB(Red As Integer, Green As Integer, Blue As Integer) As Long

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.

like image 91
Mathieu Guindon Avatar answered Sep 28 '22 07:09

Mathieu Guindon


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.

like image 22
iDevlop Avatar answered Sep 28 '22 08:09

iDevlop