Voici une question "simple" (je pense):
Comment puis-je mettre en forme un nombre sous forme de texte avec un nombre variable de chiffres? Quelque chose comme:
Dim N as Integer Dim INPUT as Integer: INPUT = 341 Dim OUPUT as String OUTPUT = Format(INPUT, "00...0")
Où "00...0" a N chiffres. Par exemple, si N = 7 , je veux OUTPUT = "0000341" . Puis-je faire quelque chose comme ça sur VBA ? Je ne trouve pas de solution pour ça ... Merci.
3 Réponses :
Je créerais une fonction simple pour y parvenir:
Debug.Print FormatToLength(341, 7) 0000341
Production:
Public Function FormatToLength(number As Long, length As Long) As String
Dim returnValue As String
returnValue = Application.Rept("0", length) & number
returnValue = Right(returnValue, length)
FormatToLength = returnValue
End Function
Cela crée une longueur de 0 répété et ajoute le nombre à la fin. Il utilise ensuite Right pour réduire la taille du retour à la longueur souhaitée.
Merci. C'est une solution élégante!
Cela ne peut pas être la meilleure façon de le faire, mais voici un moyen simple:
Dim N as Integer
Dim input_value as Integer
Dim OUPUT as String
Dim formatstring as String
N = 4
input_value = 341
'assumes N is an integer > 0
For i = 1 to N
formatstring = formatstring + "0"
Next i
OUTPUT = Format(input_value, formatstring)
& doit être utilisé pour concaténer, pas + .
Voici un moyen qui ne dépend pas de l'objet Application:
Option Explicit Private Sub Command1_Click() MsgBox FormatToLength(341, 7) End Sub Private Function FormatToLength(ByVal Value As Variant, ByVal Length As Long) As String FormatToLength = Format(Value, String(Length, "0")) End Function
IMO encore plus élégante :-)
Cela devrait être la réponse évidente.
OUTPUT = Format(INPUT, Application.Rept("0",N))@ScottCraner, si simple! Merci!!