如何根据用户窗体文本框输入将光标移动到工作表中的行?

时间:2019-06-04 17:47:53

标签: excel vba

我正在尝试为某些工单创建一个计划工具,并且我已经有一张用这些工单名称填写的Excel工作表。我希望有一个用户打开一个用户窗体,并在文本框中输入订单的名称,然后使工作表上的光标移动到与该订单相对应的行。有办法吗?

我曾经考虑过使用列表框,但是如果可能的话,我想使用文本框。

1 个答案:

答案 0 :(得分:0)

在单个字段中使用用户窗体似乎有点麻烦,而InputBox则是这样的:

Sub findOrder()

Dim ws As Worksheet: Set ws = ActiveWorkbook.Sheets("Sheet Name Here")
Dim lRow As Long: lRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row 'get last row at column A - assuming is populated

restartOrder:
Dim strOrder As String: strOrder = InputBox("Please input your order name", "Let's find the order")
Dim rngOrder As Range

Set rngOrder = ws.Range("A1:A" & lRow).Find(strOrder) 'Find the order, assuming they are in column A

If Not rngOrder Is Nothing Then '
    rngOrder.Select 'Select the order range
Else
    Dim answer As Integer: answer = MsgBox("Order wasn't found, want to try again?", vbYesNo + vbQuestion, "Not found")
    If answer = vbYes Then
        GoTo restartOrder 'restart the search
    End If
End If

End Sub

编辑:添加了对找不到订单的更好处理。

EDIT2:也添加一个用户窗体选项...向您的用户窗体中添加一个CommandButton和一个TextBox

Private Sub CommandButton1_Click()
    findOrder TextBox1.Value
End Sub

Sub findOrder(strOrder As String)

Dim ws As Worksheet: Set ws = ActiveWorkbook.Sheets("Sheet Name Here")
Dim lRow As Long: lRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row 'get last row at column A - assuming is populated

restartOrder:
Dim rngOrder As Range

Set rngOrder = ws.Range("A1:A" & lRow).Find(strOrder) 'Find the order, assuming they are in column A

If Not rngOrder Is Nothing Then '
    rngOrder.Select 'Select the order range
Else
    Dim answer As Integer: answer = MsgBox("Order wasn't found, want to try again?", vbYesNo + vbQuestion, "Not found")
    If answer = vbYes Then
        Exit Sub
    Else
        Unload Me
    End If
End If

End Sub