添加到查询结果

时间:2014-12-31 17:05:33

标签: vba ms-access

我写了以下程序,以便添加" 1"我们分配给进入办公室的邮件的代码。用户在表单上输入输入,查询将返回为州和公司分配的最后一个代码。该程序应该将该数字增加1.示例TN08801401(TN - COCODE 0880年 - 14 - 序列01)现在应为TN08801402。

只要查询带来了结果,程序就可以正常工作。如果答案是null(意味着它是我们拥有的第一个州/公司/邮件,那么我希望程序创建代码。例如WA08801501。

问题是它只给我一个errorsub例程而不是基本程序。

谢谢,

以下代码如下:

Private Sub form_load()
Dim qryrslt As String
Dim State As String
Dim num As String
Dim num1 As Integer
Dim num2 As Integer
Dim num3 As String
Dim total As String
Dim CoNo As String
Dim yearseq As String

On Error GoTo errorsub


qryrslt = DLookup("[idkey]", "assignment_qry")
State = Left(qryrslt, 6)
num = Right(qryrslt, 4)
If IsNumeric(num) Then
    num1 = CInt(num)
Else
    num1 = 0
End If
num2 = num1 + 1
num3 = CStr(num2)
total = State + num3

Me.TxtIdKey = total


errorsub:
    State = Forms!assignment_form!CmbState
    CoNo = Forms!assignment_form!CmbCompany
    yearseq = 1501
    total = State + CoNo + yearseq
    Me.TxtIdKey = total

3 个答案:

答案 0 :(得分:1)

将字段连接在一起总是更简单,而不是将它们分开。您的“idkey”似乎是由多个值组成的单个字段。最好为每个值使用单独的字段,并根据需要连接它们。假设你的表是tblPrograms。字段可以是ProgState(文本),ProgCode(文本),ProgYear(整数),ProgSequence(整数)。无论您需要它,您都可以连接ProgState& “ - ”& ProgCode& ProgYear& ProgSequence。获得下一个序列是一个简单的查找。

Dim intNewSequence as Integer 
intNewSequence = Nz(DMax("ProgSequence", "tblPrograms", "ProgState ='" & Forms!assignment_form!CmbState & "' AND ProgCode = '" & Forms!assignment_form!CmbCompany & "' AND ProgYear = " & Forms!assignment_form!ProgYear), 0) + 1 

此外,这使得任何可以在where子句中使用任何这些字段的查询效率更高。

答案 1 :(得分:0)

我认为你需要在分配State&之前进行空检查。 NUM。像这样排序:

if (qryslt is not null) 
{State = Left(qryrslt, 6)
num = Right(qryrslt, 4)
If IsNumeric(num) Then
    num1 = CInt(num)
Else
    num1 = 0
End If
num2 = num1 + 1
num3 = CStr(num2)
total = State + num3

Me.TxtIdKey = total}

很抱歉,如果语法不适合vb - 它已经有一段时间了,但我希望你明白这一点。

答案 2 :(得分:0)

我将添加分为两个步骤以使其工作。第1步是按顺序查找最后一个或创建默认值:

Private Sub Command17_Click()

Dim Qry As String
Dim State As String
Dim num As String
Dim num1 As Integer
Dim num2 As Integer
Dim num3 As String
Dim total As String
Dim CoNo As String
Dim yearseq As String

Qry = "" & DLookup("IDKEY", "Assignment_qry")

If Qry = "" Then
    State = Forms!assignment_form!CmbState
    CoNo = Forms!assignment_form!CmbCompany
    yearseq = 1500
    total = State + CoNo + yearseq
    Me.TxtAssignment = total
Else
    Me.TxtAssignment = Qry
End If

End Sub

然后我又添加了一个步骤: Private Sub form_load()

Dim qryrslt As String
Dim State As String
Dim num As String
Dim num1 As Integer
Dim num2 As Integer
Dim num3 As String
Dim total As String
Dim CoNo As String
Dim yearseq As String

qryrslt = Forms!assignment_form!TxtAssignment

State = Left(qryrslt, 6)
num = Right(qryrslt, 4)
    If IsNumeric(num) Then
    num1 = CInt(num)
    Else
    num1 = 0
    End If
num2 = num1 + 1
num3 = CStr(num2)
total = State + num3
Me.TxtIdKey = total
Me.TxtCompany = Mid(State, 3, 5)
Me.TxtCoName = DLookup("Name", "Newentry_coname_qry")