Stockcheck для обновления таблицы запасов - PullRequest
0 голосов
/ 20 февраля 2012

Итак, мой проект идет хорошо, и я создал новую форму, чтобы пользователь мог вручную вводить уровни запасов после отбора.

Кодировка, которую я имею до сих пор, выглядит следующим образом

Private Sub StockTake_Click()

'Introduce items and variables
Dim Carling As Integer
Dim Carlsburg As Integer
Dim IPA As Integer
Dim Strongbow As Integer
Dim RevJames As Integer
Dim Becks As Integer
Dim WKDBlue As Integer
Dim WKDRed As Integer
Dim SmirnoffIce As Integer
Dim KoppaburgPear As Integer
Dim KoppaburgSum As Integer
Dim Bulmers As Integer
Dim Vodka As Integer
Dim Gin As Integer
Dim Sherry As Integer
Dim Sambuca As Integer
Dim Rum As Integer
Dim Port As Integer
Dim Whiskey As Integer
Dim Baileys As Integer
Dim Jagermeister As Integer
Dim Martini As Integer
Dim CokeCan As Integer
Dim Coke As Integer
Dim LemonadeCan As Integer
Dim Lemonade As Integer
Dim Squash As Integer
Dim Tonic As Integer
Dim RedBull As Integer
Dim Nuts As Integer
Dim Crisps As Integer
Dim SQLError As String
Dim SQLDelete As String
Dim SQLUpdate As String
Dim SQLBackup As String
Dim PubStock As Integer

'define items. these "Txtname" are text boxes on the form that the user can enter the values into... already this seems like a massive 'code.
Carling = txtCarling
Carlsburg = txtCarlsburg
IPA = txtIPA
Strongbow = txtStrongbow
RevJames = txtRevJames
Becks = txtBecks
WKDBlue = txtWKDBlue
WKDRed = txtWKDRed
SmirnoffIce = txtSmirnoffIce
KoppaburgPear = txtKopPear
KoppaburgSum = txtKopSum
Bulmers = txtBulmers
Vodka = txtVodka
Gin = txtGin
Sherry = txtSherry
Sambuca = txtSambuca
Rum = txtRum
Port = txtPort
Whiskey = txtWhiskey
Baileys = txtBaileys
Jagermeister = txtJagermeister
Martini = txtMartini
CokeCan = txtCokeCan
Coke = txtCokeDra
LemonadeCan = txtLemonadeCan
Lemonade = txtLemonadeDra
Squash = txtSquash
Tonic = txtTonic
RedBull = txtRedBull
Nuts = txtNuts
Crisps = txtCrisps

'introduce SQL coding
SQLDelete = "DELETE * FROM TblStock"

SQLUpdate = "update the tblstock with the values from the form based on the name of the product. tblStock contains StockID*, ProductID and stockLevel which is just the added stock values, not the on hand stock. thus the new value inputed on the form should replace all current values in the table. "

SQLBackup = "export all data in tblStock to update values in an excel table, ie, add to the data allready there, not replace it."

'Start actual coding
If Carling = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If Carlsburg = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If IPA = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If Strongbow = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If RevJames = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If Becks = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If WKDBlue = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If WKDRed = Null Then MsgBox "Plese Fill in all areas of the form to complete the  Stock Take and try again" Else
If SmirnoffIce = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If KoppaburgPear = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If KoppaburgSum = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If Bulmers = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If Vodka = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If Gin = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If Sherry = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If Sambuca = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If Rum = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If Port = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If Whiskey = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If Baileys = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If Jagermeister = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If Martini = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If CokeCan = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If Coke = Null Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again" Else
If LemonadeCan = Null Then MsgBox "Please Fill in all areas of the form to complete the Stock Take and try again" Else
If Lemonade = Null Then MsgBox "Please Fill in all areas of the form to complete the Stock Take and try again" Else
If Squash = Null Then MsgBox "Please Fill in all areas of the form to complete the Stock Take and try again" Else
If Tonic = Null Then MsgBox "Please Fill in all areas of the form to complete the Stock Take and try again" Else
If RedBull = Null Then MsgBox "Please Fill in all areas of the form to complete the Stock Take and try again" Else
If Nuts = Null Then MsgBox "Please Fill in all areas of the form to complete the Stock Take and try again" Else
If Crisps = Null Then MsgBox "Please Fill in all areas of the form to complete the Stock Take and try again" Else PubStock = 1


If PubStock = 1 Then DoCmd.RunSQL SQLBackup
DoCmd.SetWarnings False
DoCmd.RunSQL SQLDelete
DoCmd.SetWarnings True
DoCmd.RunSQL SQLUpdate

If PubStock <> 1 Then MsgBox "Plese Fill in all areas of the form to complete the Stock Take and try again"

End Sub

kk, кроме того, что я пропускаю два SQL-запроса, кто-нибудь может увидеть какие-либо другие проблемы с кодированием? оно кажется слишком большим, и я чувствую, что серьезно упускаю что-то важное или очевидное, что сделало бы это более управляемым.

Кроме того, что он довольно большой, и я думаю, что у меня огромный сегмент «если», если не сказать больше, может ли кто-нибудь помочь мне с SQL, который может использоваться для SQLUpdate? Я боюсь, что это будет большой кусок ... должен быть более простой способ, чем этот ...: (

Может присоединить базу данных, если это может помочь.

Спасибо Sam

1 Ответ

3 голосов
/ 20 февраля 2012

Вы можете сделать это намного проще. Сначала легче кодировать, а потом легче поддерживать.

Создать таблицу, tblStockItems , с 2 полями: item_id (первичный ключ); и item_name.

item_id item_name
      1 Baileys
      2 Becks
      3 Bulmers

Создать другую таблицу, tblScratchInventory , с 2 числовыми полями: item_id; и количество.

Создайте этот запрос и сохраните его как qryScratchInventory :

SELECT
    inv.item_id,
    items.item_name,
    inv.quantity
FROM
    tblScratchInventory AS inv
    INNER JOIN tblStockItems AS items
    ON inv.item_id = items.item_id
ORDER BY items.item_name;

Создайте непрерывную форму, которая использует qryScratchInventory в качестве источника записи. Установите для свойств формы «Разрешить добавления» и «Разрешить удаление» значение «Нет». Во время открытия формы вы можете «освежить» tblScratchInventory, чтобы подготовить ее к записи нового набора значений инвентаризации.

Private Sub Form_Open(Cancel As Integer)
    Dim db As DAO.Database
    Dim strSql As String
    Set db = CurrentDb
    strSql = "DELETE FROM tblScratchInventory;"
    db.Execute strSql, dbFailOnError
    strSql = "INSERT INTO tblScratchInventory ( item_id )" & vbCrLf & _
        "SELECT tblStockItems.item_id" & vbCrLf & _
        "FROM tblStockItems;"
    db.Execute strSql, dbFailOnError
    Set db = Nothing
    Me.Requery
End Sub

Вы должны также включить обработчик ошибок для решения любых проблем, которые dbFailOnError появляются.

Добавьте командную кнопку cmdDone в нижний колонтитул формы. Используйте этот код в качестве события клика.

Private Sub cmdDone_Click()
    Dim lngNumNulls As Long
    Dim strNullItems As String
    Dim strMsg As String

    If Me.Dirty Then Me.Dirty = False
    lngNumNulls = DCount("*", "tblScratchInventory", "quantity Is Null")
    Select Case lngNumNulls
    Case 0
        ' do what you need here '
        ' then close the form: '
        DoCmd.Close acForm, Me.name
    Case Is <= 6 ' list individual items if not too many of them '
        Dim rs As DAO.Recordset
        Dim db As DAO.Database
        Dim strSql As String
        strSql = "SELECT item_name" & vbCrLf & _
            "FROM qryScratchInventory" & vbCrLf & _
            "WHERE quantity Is Null" & vbCrLf & _
            "ORDER BY item_name;"
        Set db = CurrentDb
        Set rs = db.OpenRecordset(strSql)
        With rs
            Do While Not .EOF
                strNullItems = strNullItems & vbCrLf & !item_name
                .MoveNext
            Loop
            .Close
        End With
        Set rs = Nothing
        Set db = Nothing
        strMsg = "Please input quantities for these items: " & strNullItems
    Case Else
        strMsg = "Please input quantities for all items."
    End Select
    If Len(strMsg) > 0 Then
        MsgBox strMsg
    End If
End Sub

Я не уверен, что вы хотите сделать со значениями инвентаря после того, как убедитесь, что все элементы запасов имеют ненулевые значения (Случай 0, «делайте то, что вам нужно здесь» в cmdDone_Click). Возможно, вы хотите, чтобы оператор UPDATE переносил количества в другую таблицу (TblStock?). Или, возможно, вы можете основать форму на запросе TblStock вместо использования qryScratchInventory в качестве промежуточного шага.

...