字符串末尾的增量编号

时间:2017-01-16 09:29:55

标签: vba excel-vba excel

我的字符串格式为Cells(i, 6) & ("-000") & (q)。这里Cells(i,6).value是一个整数。

我想从它所在的字符串中添加1到q

ElseIf k > 0 Then  
    Sht1.Cells(erow, 3) = CInt(sht3.Cells(i, 5).value) + 1  
    Sht1.Cells(erow, 4) = CInt(sht3.Cells(i, 6).value) + 1  
    Sht1.Cells(erow, 1) = Sht1.Cells(erow - 1, 1).value + 1   
End If

2 个答案:

答案 0 :(得分:0)

尝试用以下代码替换您的代码:

If k > 0 Then

    Sht1.Cells(erow, 3) = CInt(sht3.Cells(i, 5).value) + 1
    Debug.Print CInt(sht3.Cells(i, 5).value)

    Sht1.Cells(erow, 4) = CInt(sht3.Cells(i, 6).value) + 1
    Debug.Print CInt(sht3.Cells(i, 6).value)

    Sht1.Cells(erow, 1) = Sht1.Cells(erow - 1, 1).value + 1
    Debug.Print Sht1.Cells(erow - 1, 1).value

End If

看看它在哪里打破。看看眼前的窗口。可能价值不是数字。

如果你稍微编辑一下代码,你可能会得到你想要的东西:

Public Sub TestMe

If k > 0 Then

    Sht1.Cells(erow, 3) = IncreaseWithOne(sht3.Cells(i, 5).value)

End If

End Sub

Public Function IncreaseWithOne(strValue As String) As String

    Dim myVal  As Long

    myVal = Split(strValue, "-")(1)
    IncreaseWithOne = Split(strValue, "-")(0) & "-" & Format(myVal + 1, "0000")

End Function

但如果您根据需要编辑问题,那真的会更好。例如,您希望拆分字符串25-00001,强制转换为整数并递增第二部分并返回25-00002。因为任何编程语言都不支持向字符串添加整数。

答案 1 :(得分:0)

根据您的其他问题(在底部链接),我们知道您要增加的数字始终是右手4个字符,因此您可以使用Right来隔离数字部分。我还认为你现在采取了不同的方法,并分别存储增量值。但是作为参考,你可以这样做:

Dim myString as String
myString = "25-0003"

' Assume there is always a single dash before the number to increment
' This means we can use Split to create two parts, before and after "-"

Dim myVal as Integer
myVal = Val(Split(myString, "-")(1)) 
' >> myVal = 3

myVal = myVal + 1
' >> myVal = 4

myString =  Split(myString,"-")(0) & "-" & Format(myVal, "0000")
' >> myString = "25-0004"

因此,要编辑实际代码,将上述代码实现为函数,它就变为

Sub ThisIsYourSub()

    If k > 0 Then  
        Sht1.Cells(erow, 3) = IncrementString( sht3.Cells(i, 5).value )
        Sht1.Cells(erow, 4) = IncrementString( sht3.Cells(i, 6).value )  
        Sht1.Cells(erow, 1) = IncrementString( Sht1.Cells(erow - 1, 1).value)   
    End If

End Sub

Function IncrementString(ByVal myString as String) as String

    ' You should have some error handling in here!

    Dim myVal as Integer
    myVal = Val(Split(myString, "-")(1)) + 1

    IncrementString = Split(myString,"-")(0) & "-" & Format(myVal, "0000")

End Function

Split文档:

https://msdn.microsoft.com/en-us/library/office/gg278528.aspx

您的其他问题,包括使用上述Format功能的详细信息:

Standard pattern of string is like 16-000q. Use leading zeros to create 4 digit string from q