What code should I use in visual basic for a macro...?

Bárbara Rondón 0 Reputation points
2023-07-02T03:43:57.95+00:00

What code should I use in visual basic for a macro, in which I want it to not allow me to save the same product that is already registered in the products table?

Excel
Excel
A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
2,076 questions
Office Development
Office Development
Office: A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.Development: The process of researching, productizing, and refining new or existing technologies.
4,146 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Tanay Prasad 2,140 Reputation points
    2023-07-03T05:48:40.8733333+00:00

    Hi,

    You can use this VBA code to run a check before saving the data in your Excel macro to prevent saving a product that is already registered in your products table-

    Sub SaveProduct()     Dim ws As Worksheet     Dim productTable As ListObject     Dim productName As String     Dim productRange As Range          ' Set the worksheet containing the products table     Set ws = ThisWorkbook.Worksheets("Sheet1") ' Replace "Sheet1" with the actual name of your worksheet          ' Set the products table as a ListObject (assuming it's a structured table)     Set productTable = ws.ListObjects("Table1") ' Replace "Table1" with the actual name of your table          ' Get the product name from the user     productName = InputBox("Enter the product name:")          ' Check if the product already exists in the table     Set productRange = productTable.ListColumns("Product").DataBodyRange     If Not IsError(Application.Match(productName, productRange, 0)) Then         MsgBox "Product already exists in the table.", vbExclamation         Exit Sub     End If          ' Save the product to the table     productTable.ListRows.Add     productTable.ListColumns("Product").Range.Cells(productTable.ListRows.Count).Value = productName          MsgBox "Product saved successfully.", vbInformation End Sub 
    

    You will be prompted to enter the product name by this macro. The "Product" column is then searched for a match to see if the product is already present in the products table. A message is shown and the macro ends without saving if a match is found. If there isn't a match, the item is added to the table and a success message is shown.

    But, you'll need to customize the code to match the names of your worksheet, table, and columns accordingly.

    Best Regards.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.