[英]If Else statement only working for the last row of data in Excel VBA Userform
我正在為聽起來很簡單的事情而苦苦掙扎,但我的代碼有問題。
當我在文本框 1 中鍵入“序列號”時,我有一個帶有 2 個文本框的用戶表單,如果序列號與工作表中“RMA”列中的現有字段匹配,則文本框 2 中的“RMA 編號”會自動填充。
如果不匹配,我希望 textbox2 清除或說“不匹配”
我做了 If-Then-Else 類型的代碼,但它似乎只適用於目前的最后一個條目......
我需要在我的代碼中更改什么,以便它可以匹配所有條目並在序列號不匹配時清除?
'Autopopulate RMA# with Serial Number
Private Sub SN_TextBox1_Change()
Dim serial1_id As String
serial1_id = UCase(Trim(SN_TextBox1.Text))
lastrow = Worksheets("RMA Tracker").Cells(Rows.Count, 1).End(xlUp).Row
For i = 1 To lastrow
If UCase(Worksheets("RMA Tracker").Cells(i, 4).Value) = serial1_id Then
RMA_TextBox1.Text = Worksheets("RMA Tracker").Cells(i, 1).Value
Else
RMA_TextBox1.Value = ""
End If
Next i
End Sub
我認為您可以使用Find()
方法來實現您的目的。 下面的代碼將從 RMA 列(D:D)
中找到TextBox1
值。 如果找到匹配項,那么它將從Column A:A
返回值以匹配行到TextBox2
。 如果沒有匹配,它將向TextBox2
顯示No Match
消息。
Private Sub CommandButton1_Click()
Dim RMA As String
Dim Rng As Range
RMA = Me.TextBox1
If Trim(RMA) <> "" Then
With Sheets("RMA Tracker").Range("D:D") 'D:D for column 4
Set Rng = .Find(What:=RMA, _
After:=.Range("A1"), _
Lookat:=xlWhole, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False)
If Not Rng Is Nothing Then
Me.TextBox2 = Rng.Offset(0, -3)
Else
Me.TextBox2 = "No Match"
End If
End With
End If
End Sub
RMA_TextBox1
的屬性中將MultiLine
設置為True
。編碼
Private Sub SN_TextBox1_Change()
Const wsName As String = "RMA Tracker"
Const FirstRow As Long = 1
Const RMACol As Variant = "A"
Const IdCol As Variant = "D"
Const IfNot As String = "No Match"
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Worksheets(wsName)
Dim LastRow As Long: LastRow = ws.Cells(ws.Rows.Count, IdCol).End(xlUp).Row
Dim SerialID As String: SerialID = Trim(SN_TextBox1.Value)
Dim i As Long, Result As String
For i = FirstRow To LastRow
If StrComp(ws.Cells(i, IdCol).Value, SerialID, vbTextCompare) = 0 Then
If Result <> "" Then
Result = Result & vbLf & ws.Cells(i, RMACol).Value
Else
Result = ws.Cells(i, RMACol).Value
End If
End If
Next i
If Result <> "" Then
RMA_TextBox1.Value = Result
Else
RMA_TextBox1.Value = IfNot
End If
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.