excelvba

ComboBox filled from a sheet: get the remaining cells and place them in other sheets


I have a combobox in a sheet called "Sheet_Invoice_Template" that gets the information from another sheet called "Sheet_Contacts" enter image description here

I want to get the rest of the cells in the "Sheet_Contacts" sheet depending on the item I have selected to place them in other sheets

enter image description here

This is my code but it doesn't do anything or throw an error.

Dim selectedRow As Long
 Dim ws As Worksheet
 Set ws = ThisWorkbook.Sheets("Sheet_Invoice_Template")
 selectedRow = Me.ComboBoxClientes.ListIndex + 2
 MsgBox "valor elegido: " & selectedRow
 Dim cellValue1 As Variant
 Dim cellValue2 As Variant
 cellValue1 = ws.Cells(selectedRow, "B").Value
 cellValue2 = ws.Cells(selectedRow, "C").Value
 MsgBox "valor direccion: " & cellValue1

Solution

  • I think you're trying to retrieve data from Sheet_Contacts based on a ComboBox selection in Sheet_Invoice_Template, but your code is reading from the wrong sheet. Update your code to reference Sheet_Contacts when accessing cell values, like wsContacts.Cells(...), and ensure you're using the correct row index from the ComboBox. Also, verify that the ComboBox is populated correctly and the ListIndex is valid before accessing the data.

    Not tested:

    Private Sub ComboBoxClientes_Change()
        Dim selectedRow As Long
        Dim wsContacts As Worksheet
        Dim wsInvoice As Worksheet
        Dim cellValue1 As Variant
        Dim cellValue2 As Variant
    
        ' Set references to the worksheets
        Set wsContacts = ThisWorkbook.Sheets("Sheet_Contacts")
        Set wsInvoice = ThisWorkbook.Sheets("Sheet_Invoice_Template")
    
        ' Get the selected row index from the ComboBox
        selectedRow = Me.ComboBoxClientes.ListIndex + 2 ' Assuming headers are in row 1
    
        ' Check if a valid selection was made
        If selectedRow >= 2 Then
            ' Get values from the Sheet_Contacts
            cellValue1 = wsContacts.Cells(selectedRow, 2).Value ' Column B
            cellValue2 = wsContacts.Cells(selectedRow, 3).Value ' Column C
    
            ' Display the values or assign them to cells in another sheet
            MsgBox "Address: " & cellValue1 & vbCrLf & "Phone: " & cellValue2
    
            ' Example: write to Sheet_Invoice_Template
            wsInvoice.Range("B10").Value = cellValue1
            wsInvoice.Range("B11").Value = cellValue2
        Else
            MsgBox "Please select a valid client."
        End If
    End Sub