在表中查找特定记录

时间:2018-08-21 15:07:09

标签: excel vba excel-vba

我正在寻找仅查找某些记录并进行相应处理。我有一个名为Locations的表,其中一列标记为Location。当前,当我运行宏时,我的代码可以处理所有位置。但是,我想写一个仅在某些位置(一个范围)运行的宏的变体。位置值全为2个字母,后跟5个数字。 例如:CA10020

我想做的是提示输入开始和结束位置值,然后仅处理那些值。 示例:CA10001至CA13240 这些值之前和之后的所有内容都将被忽略...但是这些值及其之间的所有内容都将得到处理。

通常我有一个很好的主意,从哪里开始,通过反复试验,我可以找出其余的问题。在这种情况下,我很困惑该从哪里开始。如您所知,我不是VBA专家。

我目前有这段代码可以处理所有记录,而这不是我现在要做的:

For i = 1 To Range("Locations").Rows.Count
    Range("F3").Value = Range("Locations[Location]")(i)
    'I have other code here that handles the new value of cell F3
Next i

更新: 我添加了以下代码:

Dim Start_Location As Variant
Dim End_Location As Variant
Start_Location = InputBox("What is the starting location?")
End_Location = InputBox("What is the ending location?")

...但是我现在不知道如何处理这些值。

2 个答案:

答案 0 :(得分:0)

Dim Start_Location As Variant
Dim End_Location As Variant
Start_Location = InputBox("What is the starting location?")
End_Location = InputBox("What is the ending location?")

For i = 1 To Range("Locations").Rows.Count
    If Range("Locations[Location]")(i) >= Start_Location And Range("Locations[Location]")(i) <= End_Location Then

        Range("F3").Value = Range("Locations[Location]")(i)

        'Code to handle the new value of cell F3
    End If

Next i

答案 1 :(得分:0)

我建议使用Match()查找第一个和最后一个位置,以减少循环的运行时间。

Option Explicit

Public Sub ProcessLocationFromTo()
    Dim FirstLocation As Variant
    Dim LastLocation As Variant
    FirstLocation = InputBox("What is the starting location?")
    LastLocation = InputBox("What is the ending location?")

    Dim RngLocation As Range
    Set RngLocation = Range("Locations[Location]")

    Dim FirstRow As Long
    On Error GoTo ERR_FIND_LOCATION
    FirstRow = Application.WorksheetFunction.Match(FirstLocation, RngLocation, 1)
    On Error GoTo 0

    Dim LastRow As Long
    On Error GoTo ERR_FIND_LOCATION
    LastRow = Application.WorksheetFunction.Match(LastLocation, RngLocation, 1)
    On Error GoTo 0

    Dim i As Long
    For i = FirstRow To LastRow
        Range("F3").Value = RngLocation(i)

        'Code to handle the new value of cell F3
    Next i


    Exit Sub

ERR_FIND_LOCATION:
    MsgBox "The location was out of range." & vbCrLf & "It must be between """ & RngLocation(1) & """ and """ & RngLocation(RngLocation.Count) & """."
    Exit Sub
End Sub

注意,这仅在表格按位置排序时有效!否则,在运行该过程之前,您将需要按位置排序:

With ListObjects("Locations").Sort
    .SortFields.Clear
    .SortFields.Add2 Key:=Range("Locations[[#All],[Location]]"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With