搜索时在列之间切换

时间:2016-01-05 08:17:59

标签: excel-vba vba excel

我在我的程序中使用此代码在excel表中搜索,但仅在A1列中,如果我想添加命令或函数以帮助在A1,B1,C1,...列之间进行更改,谢谢提前。

Private Sub cmdsearch_Click()
    blnNew = False
        txtChem1.Text = ""
        txtChem2.Text = ""
        txtChem3.Text = ""
TRows = Worksheets("Data").Range("A1").CurrentRegion.Rows.Count            
    For i = 2 To TRows
        If Val(Trim(ComboBox1.Text)) = Val(Trim(Worksheets("Data").Cells(i, 1).Value)) Then    
        txtChem1.Text = Worksheets("Data").Cells(i, 1).Value
        txtChem2.Text = Worksheets("Data").Cells(i, 2).Value
        txtChem3.Text = Worksheets("Data").Cells(i, 3).Value  
        Exit For
        End If    
    Next i
    If Trim(txtChem1.Text) = "" Then
        cmdSave.Enabled = False
        cmdDelete.Enabled = False
        Frame2.Enabled = False
    Else
        cmdSave.Enabled = True
        cmdDelete.Enabled = True
        Frame2.Enabled = True
    End If
End Sub

1 个答案:

答案 0 :(得分:0)

您好,您可以创建一个相同的功能:

Sub Search(CellParams)
 blnNew = False
        txtChem1.Text = ""
        txtChem2.Text = ""
        txtChem3.Text = ""
TRows = Worksheets("Data").Range(CellParams).CurrentRegion.Rows.Count            
    For i = 2 To TRows
        If Val(Trim(ComboBox1.Text)) = Val(Trim(Worksheets("Data").Cells(i, 1).Value)) Then    
        txtChem1.Text = Worksheets("Data").Cells(i, 1).Value
        txtChem2.Text = Worksheets("Data").Cells(i, 2).Value
        txtChem3.Text = Worksheets("Data").Cells(i, 3).Value  
        Exit For
        End If    
    Next i
    If Trim(txtChem1.Text) = "" Then
        cmdSave.Enabled = False
        cmdDelete.Enabled = False
        Frame2.Enabled = False
    Else
        cmdSave.Enabled = True
        cmdDelete.Enabled = True
        Frame2.Enabled = True
    End If
End Sub

在按钮中,您可以使用:

Private Sub cmdsearch_Click()
   Search("A1")
End Sub