ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   Fixed length padded string (https://www.excelbanter.com/excel-programming/454438-fixed-length-padded-string.html)

RG III

Fixed length padded string
 
What's the easiest way to modify a string in a variable so that it only holds a maximum of 16 characters, and if it's less than 16 characters I want to attach asterisk "*" characters until it makes the string length 16?

Here are some before-after examples:

BEFO s = "french fries" ' Len = 12
AFTER: s = "french fries****" ' Len = 16

BEFO s = "" ' Len = 0
AFTER: s = "****************" ' Len = 16

BEFO s = "tree" ' Len = 4
AFTER: s = "tree************" ' Len = 16

BEFO s = "There are fries." ' Len = 16
AFTER: s = "There are fries." ' Len = 16

The last example has 16 characters, so there's no need to pad it.

I think I could do this simply in C/C++ with the printf() format string, but I'm looking for a quick way to do this with VBA. Thanks.

-Robert

RG III

Fixed length padded string
 
Also, if the input string is greater than 16 chars, then truncate it to just 16 characters:

BEFO s = "The quick brown fox jumps over the lazy dog." ' Len = 40
AFTER: s = "The quick brown fox " ' Len = 16




malone

Fixed length padded string
 
On 21-Sep-2019 11:19 AM, RG III wrote:
What's the easiest way to modify a string in a variable so that it only holds a maximum of 16 characters, and if it's less than 16 characters I want to attach asterisk "*" characters until it makes the string length 16?

Here are some before-after examples:

BEFO s = "french fries" ' Len = 12
AFTER: s = "french fries****" ' Len = 16

BEFO s = "" ' Len = 0
AFTER: s = "****************" ' Len = 16

BEFO s = "tree" ' Len = 4
AFTER: s = "tree************" ' Len = 16

BEFO s = "There are fries." ' Len = 16
AFTER: s = "There are fries." ' Len = 16

The last example has 16 characters, so there's no need to pad it.

I think I could do this simply in C/C++ with the printf() format string, but I'm looking for a quick way to do this with VBA. Thanks.

-Robert


How about:-

s = left(s & String(16, "*"), 16)


RG III

Fixed length padded string
 
On Friday, September 20, 2019 at 5:40:31 PM UTC-7, malone wrote:

How about:-

s = left(s & String(16, "*"), 16)


Bravo bravo! That works for me. Thanks!



All times are GMT +1. The time now is 08:28 AM.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
ExcelBanter.com