3

I'm migrating source from vb6.0 to vb.net and am struggling with this format function:

VB6.Format(text, "!@@@@@@@@@")

VB6.Format(text, "00000")

I don't understand the meaning of "!@@@@@@@@@" and "00000", and how to do the equivalent in VB.Net. Thanks

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
tedd
  • 141
  • 1
  • 9
  • [This documentation](https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/format-function-visual-basic-for-applications) is for the VBA version of that `Format` function but they work the same way, so you can get all you need from there. Once you understand what the existing format specifiers mean, you should replace that method with the standard .NET `String.Format` method. – jmcilhinney Jul 20 '21 at 06:24
  • 1
    Does this answer your question? [VB6 Format function: analog in .NET](https://stackoverflow.com/questions/2116244/vb6-format-function-analog-in-net) – GSerg Jul 20 '21 at 06:59

1 Answers1

7

This:

VB6.Format(text, "!@@@@@@@@@")

indicates that the specified text should be left-aligned within a nine-character string. Using standard .NET functionality, that would look like this:

String.Format("{0,-9}", text)

or, using the newer string interpolation, like this:

$"{text,-9}"

The second on is a little bit trickier. It's indicating that the specified text should be formatted as a number, zero-padded to five digits. In .NET, only actual numbers can be formatted as numbers. Strings containing digit characters are not numbers. You could convert the String to a number and then format it:

String.Format("{0:00000}", CInt(text))

or:

String.Format("{0:D5}", CInt(text))

If you were going to do that then it's simpler to just call ToString on the number:

CInt(text).ToString("D5")

If you don't want to do the conversion then you can pad the String explicitly instead:

text.PadLeft(5, "0"c)
jmcilhinney
  • 50,448
  • 5
  • 26
  • 46
  • In VB6 `Format(text, "00000")` works on numeric data-types only and is a no-op for strings i.e. returns `text` unchanged. – wqw Jul 20 '21 at 07:39
  • @wqw, I've never used VB6 and was not aware of that. I'll update my answer accordingly. – jmcilhinney Jul 20 '21 at 08:02
  • 1
    @wqw - that is true only when the string contains non-numerics. When the string is numeric characters, then the formatting is performed. For example, `Format("12q", "00000")` returns `"12q"`, while `Format("12", "00000")` returns `"00012"`. – MarkL Jul 20 '21 at 13:22
  • @MarkL, fortunately, I have not yet updated my answer. – jmcilhinney Jul 20 '21 at 13:47
  • @MarkL Nice catch! By now it must be obvious `String.Format("{0:00000}", CInt(text))` is not the same as `VB6.Format(text, "00000")`. – wqw Jul 30 '21 at 21:06