扫描条形码时不断在用户表单中添加新文本框

问题描述 投票:0回答:1

我正在开发一个用户表单,显示产品信息,包括条形码、产品名称和价格,所有信息均来自“产品”选项卡。最初,我设法让条形码扫描并显示第一个项目的产品名称和价格。但是,我在扫描第二个商品时遇到了问题 - 产品名称和价格标签没有更新。此外,在尝试扫描第三个项目时,新的文本框未能按预期显示。下面是我到目前为止的代码:

Private Sub BarcodeTextBox_Change()
    Dim scannedCode As String
    Dim foundProduct As Range
    
    ' Get the scanned barcode from the TextBox
    scannedCode = BarcodeTextBox.Text
    
    ' Search for the scanned product code in the "Products" worksheet
    Set foundProduct = Worksheets("Products").Columns(1).Find(What:=scannedCode, LookIn:=xlValues, LookAt:=xlWhole)
    
    If Not foundProduct Is Nothing Then
        ' Product found, retrieve information
        Dim productName As String
        Dim productPrice As Double
        
        ' Retrieve product name and price from adjacent cells
        productName = foundProduct.Offset(0, 1).Value
        productPrice = foundProduct.Offset(0, 2).Value
        
        ' Update labels to display product information
        ProductNameLabel.Caption = "Product Name: " & productName
        ProductPriceLabel.Caption = "Price: $" & Format(productPrice, "0.00")
        
        ' Add a new TextBox below BarcodeTextBox for continuous scanning
        AddNewBarcodeTextBox
        SendKeys "{TAB}", False
    Else
        ' Product not found, clear labels
        ProductNameLabel.Caption = ""
        ProductPriceLabel.Caption = ""
    End If
End Sub

Private Sub AddNewBarcodeTextBox()
    ' Add a new TextBox below BarcodeTextBox
    Dim newTextBox As MSForms.TextBox
    Set newTextBox = Me.Controls.Add("Forms.TextBox.1")
    
    With newTextBox
        .Top = BarcodeTextBox.Top + BarcodeTextBox.Height + 5 ' Position below the BarcodeTextBox
        .Left = BarcodeTextBox.Left
        .Width = BarcodeTextBox.Width
        .Height = BarcodeTextBox.Height
        .Name = "NewBarcodeTextBox"
        .TabStop = True
        .SetFocus
    End With
End Sub

下面是用户表单的图片 enter image description here

如果您需要更多信息,请告诉我。提前谢谢您!

excel vba
1个回答
0
投票

第三个隐藏在第二个下方,您不会增加第三个的顶部:

Private count As Integer

Private Sub AddNewBarcodeTextBox()
    ' Add a new TextBox below BarcodeTextBox
    Dim newTextBox As MSForms.TextBox
    Set newTextBox = Me.Controls.Add("Forms.TextBox.1")
    count = count + 1
    With newTextBox
        .Top = BarcodeTextBox.Top + (count * (BarcodeTextBox.Height + 5)) ' Position below the BarcodeTextBox
        .Left = BarcodeTextBox.Left
        .Width = BarcodeTextBox.Width
        .Height = BarcodeTextBox.Height
        .Name = "NewBarcodeTextBox" & count
        .TabStop = True
        .SetFocus
    End With
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.