尝试增加文本编号时VBA类型不匹配

时间:2013-10-04 10:35:55

标签: vba ms-access access-vba

我正在尝试在MS Access中设置一个代码,该代码会增加文本字段的最后四个位置。文本字段中的数字有七位数字。例如:

0010012

0010013

前三位代表制造商,后四位代表产品。这些是我想要增加的。我使用下面的代码,我在网上找到它,它应该工作,但我一直收到错误:“运行时错误'13':类型不匹配”

Dim varSifra As Variant
varSifra = DMax("[Sifra]", "tblProducts", "[Manufacturer] = " & Forms!frmProduct!Manufacturer)
Me.[Sifra] = Left(varSifra, 3) & Format(Val(Right(varSifra, 4)) + 1, "0000")

我尝试了没有格式化功能的代码,但是没有增加数字0010014我得到00114

3 个答案:

答案 0 :(得分:2)

这有帮助吗?

Sub Test()
    Debug.Print IncrementProduct("0010001") //Prints 0010002
    Debug.Print IncrementProduct("0010012") //Prints 0010013
    Debug.Print IncrementProduct("0010099") //Prints 0010100
End Sub


Function IncrementProduct(code As String) As String
    Dim manufacturerCode As String, padding As String, productCode As String

    manufacturerCode = VBA.Left$(code, 3)
    productCode = CInt(VBA.Right$(code, Len(code) - Len(manufacturerCode))) + 1
    padding = Application.WorksheetFunction.Rept("0", 4 - Len(productCode))

    IncrementProduct = manufacturerCode & padding & productCode
End Function

答案 1 :(得分:2)

您可以使用简单的Format调用,但输入需要首先显式转换为Long:

Function IncProductNumber(Value)
    If IsNull(Value) Then
        Let IncProductNumber = Null
    Else
        Let IncProductNumber = Format(CLng(Value) + 1, "0000000")
    End If
End Function

或者,更一般地说,可以从输入中推断出所需的填充:

Function IncTextNumber(Value)
    If IsNull(Value) Then
        Let IncTextNumber = Null
    Else
        Let IncTextNumber = Format(CLng(Value) + 1, String$(Len(Value), "0"))
    End If
End Function

IncTextNumber(" 0123")将生成" 0124&#34 ;, IncTextNumber(" 00999")将生成" 01000"等等。

答案 2 :(得分:1)

Dim tempManProd As String, tempNumToInc As Integer

tempManProd = 'get the value you are wanting to increment
tempNumToInc = CInt(right(tempManProd, 4))
tempNumToInc = tempNumToInc + 1

'This will make sure that the 0s get added back to the front of the product
Do While (Len(tempManProd & "") + Len(tempNumToInc & "")) < 7
  tempManProd = tempManProd & "0"
Loop

tempManProd = tempManProd & CStr(tempNumToInc)