MidB Function
The MidB function returns a Variant (String) containing a specified number of bytes from a string.
This function operates on byte positions rather than character positions, which is important when working
with ANSI strings or when you need byte-level control over string manipulation.
Syntax
MidB(string, start[, length])
Parameters
string- Required.Stringexpression from which bytes are returned.start- Required.Long. TheByteposition in string at which the part to be taken begins (1-based).length- Optional.Long. Number of bytes to return. If omitted or if there are fewer thanlengthbytes in the text (including the byte atstart), all bytes from the start position to the end of the string are returned.
Return Value
Returns a Variant (String) containing the specified byte sequence from the input string.
Behavior
- If
startis greater than the number of bytes instring,MidBreturns a zero-length string (""). - If
startis less than 1, a runtime error occurs. - If
lengthis negative, a runtime error occurs. - The first byte in the string is at position 1.
- When working with DBCS (Double-Byte Character Set) strings,
MidBcan split multi-byte characters if not used carefully.
Difference from Mid
The MidB function operates on byte positions, while the Mid function operates on character positions.
For single-byte character sets (like ASCII), they behave identically. For multi-byte character sets
(like Unicode or DBCS), MidB provides byte-level access which can be useful for binary data manipulation
or low-level string operations.
Examples
' Extract 3 bytes starting at byte position 2
Dim result As Variant
result = MidB("Hello World", 2, 3) ' Returns "ell"
' Extract from byte position 7 to the end
result = MidB("Hello World", 7) ' Returns "World"
' Start position beyond string length
result = MidB("Hi", 10) ' Returns ""