Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
872 views
in Technique[技术] by (71.8m points)

string - Any method equivalent to PadLeft/PadRight?

Just wondering, is there any equivalent in VBA to VB .NET's PadLeft and PadRight methods?

As of right now, whenever I want to take a string and make it a fixed length with leading spaces, I do a For...Next loop based on the string's length.

For example, I would use the following code to format a string to 8 characters with leading spaces:

intOrdNoLen = Len(strOrdNo)
For i = 1 To (8 - intOrdNoLen) Step 1
    strOrdNo = " " & strOrdNo
Next

Is there a way to do this same thing in fewer lines in VBA?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't believe there are any explicit PADLEFT or PADRIGHT functions, but you can use a combination of SPACE and LEFT or RIGHT to prepend spaces to your string, and then grab the right X number of characters.

PADLEFT

strOrdNo = RIGHT(Space(8) & strOrdNo, 8)

If you want a character instead of spaces, you can use STRING instead of space (the example below left-pads with X):

strOrdNo = RIGHT(String(8, "X") & strOrdNo, 8)

PADRIGHT

strOrdNo = LEFT(strOrdNo & Space(8), 8)

strOrdNo = LEFT(strOrdNo & String(8, "X"), 8)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...