在字符串中保留前导0 - 数字 - 字符串转换

时间:2015-04-28 17:45:31

标签: string excel vba excel-vba type-conversion

我正在开发一个用于处理文档跟踪表的宏。我使用一个按钮提示用户输入文档编号,我想根据以下编号约定指定默认编号。文档编号的前两个字符是后两年的数字(本例中为15),然后是“ - ”后跟五位序列化。

我当前的代码查看最后输入的文档并递增最后5个字符,但是切掉任何前导零,我想保留它。这是对代码的提取以生成此默认数字(假设变量“prevNCRF”是在doc中找到的先前文档名称):

    Sub codeChunkTester()

    Dim prevNCRF, defNCRFNum As String
    Dim NCRFNumAr() As String

    'pretend like we found this in the sheet.
    prevNCRF = "15-00100"

    'split the string into "15" and "00100" and throw those into an array.
    NCRFNumAr() = Split(prevNCRF, "-")

    'reconstruct the number by reusing the first part and dash, then converting
    'the "00100" to a number with Val(), adding 1, then back to a string with CStr().
    defNCRFNum = NCRFNumAr(0) & "-" & CStr(Val(NCRFNumAr(1)) + 1)

    'message box shows "15-101" rather than "15-00101" as I had hoped.
    MsgBox (defNCRFNum)

    End Sub

那么有人可以帮助我保留那些零吗?我想我可以包含一个循环来检查字符串的长度并添加一个前导零,直到有5个字符,但也许有更好的方法......

3 个答案:

答案 0 :(得分:3)

使用"00100"Double转换为Val会将其转换为100,因此CStr(100)会返回"100"

您需要将字符串格式化为您希望它的样子:

defNCRFNum = NCRFNumAr(0) & "-" & Format(Val(NCRFNumAr(1)) + 1, "00000")

如果需要参数化字符串的长度,可以使用String函数生成格式字符串:

Const digits As Integer = 5

Dim formatString As String
formatString = String(digits, "0")

defNCRFNum = NCRFNumAr(0) & "-" & Format(Val(NCRFNumAr(1)) + 1, formatString)

答案 1 :(得分:0)

这是我上面提到的循环解决方案。如果有人得到更好的东西,我全都耳朵!

prevNCRF = "15-00100"
NCRFNumAr() = Split(prevNCRF, "-")
zeroAdder = CStr(Val(NCRFNumAr(1)) + 1)

'loop: everytime the zeroAdder string is not 5 characters long, 
'put a zero in front of it.
Do Until Len(zeroAdder) = 5
    zeroAdder = "0" & zeroAdder
Loop

defNCRFNum = NCRFNumAr(0) & "-" & zeroAdder
MsgBox (defNCRFNum)

答案 2 :(得分:0)

defNCRFNum = NCRFNumAr(0) & "-" & Format(CStr(Val(NCRFNumAr(1)) + 1), String(Len(NCRFNumAr(1)), "0"))