Search code examples
excelvbauserform

Search column for value x and copy userform data to applicable row


I have got the below code I assigned k as the textbox value to check that it is working properly (seems it is) but it still refuses to search column A and simply executes the Else argument.

    Private Sub CommandButton1_Click()

Dim FoundCell As Range
Set FoundCell = Sheets("WATCH LOG").Range("A:A").Find(What:=WN.Value)
    k = FoundCell.Value

If k = WN.Value Then
        j = FoundCell.Row
            Sheets("WATCH LOG").Cells(j, 6).Value = Me.DMN.Value
            Sheets("WATCH LOG").Cells(j, 7).Value = Me.DWN.Value
            Sheets("WATCH LOG").Cells(j, 8).Value = Me.DOE.Value
End If
    Else
    MsgBox "WATCH NOT FOUND"

End Sub

Added note due to comment:

WN, DMN, DWN and DOE are userform text fields.


Solution

  • As far as I understand the purpose of your code, you want to find a search string as entered in the 1st textbox WN in column A and write the subsequent textbox strings DMN, DWN and DOE to a given offset within the found row.

    Some hints to multiple issues:

    • declare all your variables (use Option Explicit)
    • use fully qualified range references
    • referring to worksheets prefer the Worksheets collection, as Sheets may include shapes as well
    • be strict in indenting code to avoid wrong If .. Else ..EndIf constructions as you did (btw this would raise a compile error)
    • provide for cases where you don't find your search string e.g. via If Not FoundCell Is Nothing Then; this allows you to avoid extra checks like If k = WN.Value Then because if you found the search item, it is identical

    Furthermore I demonstrated a way to write all subsequent textbox values to a given offset of +5 columns right to the found cell in column A via Array(DMN, DWN, DOE) by one code line :)

    Option Explicit                               ' declaration head of code module
    
    Private Sub CommandButton1_Click()
    ' Purpose: find search string of 1st textbox and write subsequent strings to found row
    With ThisWorkbook.Worksheets("WATCH LOG")     ' use fully qualified range reference
        Dim FoundCell As Range
        Set FoundCell = .Range("A:A").Find(What:=WN, LookAt:=xlWhole,  MatchCase:=False)
    
        If Not FoundCell Is Nothing Then          ' search string found
            FoundCell.Offset(0, 5).Resize(1, 3) = Array(DMN, DWN, DOE)
        Else                                      ' provide for non-results
            MsgBox "WATCH NOT FOUND"
        End If
    End With
    
    End Sub