字符串末尾的增量编号

问题描述:

我的字符串格式为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 
+0

什么是你的代码的问题? – Vityata

+0

获取运行时错误13 –

尝试使用这种替代代码:

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。因为将任何编程语言都不支持将整数添加到字符串。

+0

在sht1.cells(erow,3)上中断并获得相同的错误。我的代码看起来像16-00012 –

+0

然后放在'Debug.Print CInt(sht3.Cells(i,5).value')行的最上面,并告诉直接窗口中的内容。 – Vityata

+0

它通过'debug.print并在sht1.cells上显示错误(erow,3) –

从您的其他问题(底部链接)中,我们知道您要增加的数字总是右边的4个字符,因此您可以使用Right来隔离数字部分。我也认为你现在采取了不同的方法,并分别存储增量值。供参考不过,你这是怎么可以做它:

​​

所以编辑您的实际代码,实现上述代码的功能,它成为

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

+0

如果我想MyString到一个数据范围它可以在'split function'中使用比较功能来完成? –