Home » excel » Changing a VBA code to read from a defined cell instead of a text box (Excel)

Changing a VBA code to read from a defined cell instead of a text box (Excel)

Posted by: admin May 14, 2020 Leave a comment


I have searched through this site and found a code from a user on here that is almost perfect for my application.

Private Sub TextBox1_Change()
    If InStr(2, TextBox1, "*RCBC*") > 1 Then
        Me.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0) = Me.TextBox1.Value
        Me.TextBox1.Text = ""
    End If
End Sub

This code will take the data entered in the text box and move it to the first available spot in column A once RCBC is found.

What I would like to change, is for this code to perform this task from a defined cell, not a text box. As the application for this is to receive data from a barcode scanner, and when that string is found, to move the contents. The scanner will only enter data into a cell. I have very little knowledge of VBA, but some coding background.

Thank you in advance.

How to&Answers:

Worksheet_Change() is an event, that you can get used of:

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Application.EnableEvents = False

    If Target.Cells.Count > 1 Then Exit Sub
    If InStr(2, UCase(Target.Value2), "RCBC") > 1 Then
        Target.Value2 = Target.Value2
        Target = vbNullString
    End If

    Application.EnableEvents = True

End Sub
  • added UCase(), thus it checks for RCbC and RcBc as well.
  • Application.EnableEvents = False is needed to disable the events temporarily, thus avoiding endless loop, due to writing over and over in the same cell.
  • Target.Cells.Count > 1 checks the number of selected cells.


You will need a worksheet_change event sub procedure in the same private worksheet code sheet that your TextBox1_Change was in.

sub worksheet_change(byval target as range)
    if not intersect(target, range("B1")) is nothing then
        on error goto safe_exit
        application.enableevents = false
        If InStr(2, range("B1").Value, "RCBC") > 1 Then
            Cells(Rows.Count, "A").End(xlUp).Offset(1, 0) = range("B1").Value
            range("B1") = vbnullstring
        End If
    end if
    application.enableevents = true
end sub