我的初学者代码[运行良好]使用多个IF语句。我的问题是[在我再进一步之前因为我会有很多文本框[txtbx#]这样编码有什么缺点吗?
用户将在文本框中键入40-50个短字符串,而有人将其读取给他,然后单击按钮以填充工作表列中所有匹配项的颜色;
Private Sub CommandButton1_Click()
Dim i As Integer
Dim AbbNum As String
Dim AbbNum2 As String
Dim AbbNum3 As String
Dim AbbNum4 As String
Dim AbbNum5 As String
Dim c As Integer
Dim MySheet As Worksheet
Set MySheet = Sheets(2)
c = MySheet.Cells(Rows.Count, 2).End(xlUp).Row
For i = 2 To c
AbbNum = txtbxONE.Value
If Cells(i, 1).Value = AbbNum Then
Cells(i, 1).Interior.ColorIndex = 6
End If
AbbNum2 = txtbxTWO.Value
If Cells(i, 1).Value = AbbNum2 Then
Cells(i, 1).Interior.ColorIndex = 6
End If
AbbNum3 = txtbxTHREE.Value
If Cells(i, 1).Value = AbbNum3 Then
Cells(i, 1).Interior.ColorIndex = 6
End If
AbbNum4 = txtbxFOUR.Value
If Cells(i, 1).Value = AbbNum4 Then
Cells(i, 1).Interior.ColorIndex = 6
End If
AbbNum5 = txtbxFIVE.Value
If Cells(i, 1).Value = AbbNum5 Then
Cells(i, 1).Interior.ColorIndex = 6
End If
Next i
End Sub
答案 0 :(得分:3)
如果您为文本框命名" txtbx1"," txtbx2"等,您可以执行以下操作:
Private Sub CommandButton1_Click()
Const NUM_TEXTBOXES as Long = 10 'for example....
Dim i As Long
Dim AbbNum As String, f As Range, rngSrch As Range
Set rngSrch = Sheets(2).Range("A:A")
For i = 1 To NUM_TEXTBOXES
AbbNum = Me.Controls("txtbx" & i).Value
If Len(AbbNum) > 0 Then
'EDIT: fixed typo in next line
Set f = rngSrch.Find(AbbNum, lookin:=xlvalues, lookat:=xlWhole)
If Not f Is nothing then f.Interior.ColorIndex = 6
End If
Next i
End Sub