简体   繁体   English

Excel VBA中的IF ElseIF语句

[英]IF ElseIF statements in Excel VBA

I am trying to write a script for a country-based Database search. 我正在尝试为基于国家/地区的数据库搜索编写脚本。 The search is ran on a sheet full of data called "Database" and the results pasted to a different sheet called "Results". 搜索在一个充满数据的工作表上进行,该工作表称为“数据库”,结果粘贴到另一个工作表中,称为“结果”。

The search is dependent on user-inputted variables, which I have defined as "Country", "Category" and "Subcategory": 搜索取决于用户输入的变量,我将其定义为“国家/地区”,“类别”和“子类别”:

country = Sheets("Results").Range("D5").Value
Category = Sheets("Results").Range("D6").Value
Subcategory = Sheets("Results").Range("D7").Value
finalrow = Sheets("Database").Range("A200000").End(xlUp).Row

I want the search criteria filled in by the user through a UserForm to lead to different scenarios. 我希望用户通过UserForm填写的搜索条件导致不同的情况。 As such: 因此:

1 - If the user searches for a country that is not included in the database, the search will not run and a message saying so will pop up. 1-如果用户搜索数据库中未包含的国家/地区,则搜索将不会运行,并且会弹出一条消息,提示您这样做。 I used a .Find function to so: 我使用.Find函数来做到这一点:

With Worksheets("Database")
        Set c = .Range("A:A").Find(What:=country, After:=.Cells(1, 1), _
                LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
                SearchDirection:=xlNext, MatchCase:=False)
        If Not c Is Nothing Then
        Else
            MsgBox "Unfortunately, the database does not have any sources for information in " & country & ". Please search for sources in relating to another country."
            Sheets("Results").Range("D5").ClearContents
            Sheets("Results").Range("D6").ClearContents
            Sheets("Results").Range("D7").ClearContents
            Exit Sub
        End If
    End With

2- If the user does not produce a name of a country to search for, the search will not run. 2-如果用户未提供要搜索的国家/地区名称,则搜索将不会运行。 I used an IF statement to do so: 我使用IF语句来这样做:

If country = "" Then
        Sheets("Results").Range("B10:J200000").Clear
        MsgBox "You must select a country in order to search the database. Please do so in the drop-down list provided."
        Sheets("Results").Range("D5").ClearContents
        Sheets("Results").Range("D6").ClearContents
        Sheets("Results").Range("D7").ClearContents
        Exit Sub
    End If

3 - If the user searches for a country in the database, the search runs, either listing all matches for the country or, if the user has narrowed the search by providing "Category" and "Subategory", listing only those database entries which match the three criteria. 3-如果用户在数据库中搜索国家/地区,则运行搜索,列出该国家/地区的所有匹配项;或者,如果用户通过提供“类别”和“子类别”来缩小搜索范围,则仅列出匹配的那些数据库条目这三个标准。 I have done this through an IF statement, separate from the first one: 我通过与第一个语句分开的IF语句来完成此操作:

For i = 2 To finalrow

    'If the country field is filled in and there results from the search made
    If Sheets("Database").Cells(i, 1) = country And _
        (Sheets("Database").Cells(i, 3) = Category Or Category = "") And _
        (Sheets("Database").Cells(i, 4) = Subcategory Or Subcategory = "") Then

            'Copy the headers of the "Database" sheet
            With Sheets("Database")
            .Range("A1:I1").Copy
            End With
            Sheets("Results").Range("B10:J10").PasteSpecial

            'Copy the rows of the "Database" that match the search query
            With Sheets("Database")
            .Range(.Cells(i, 1), .Cells(i, 9)).Copy
            End With
            Sheets("Results").Range("B20000").End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats

4 - As a last scenario, I want the script to react to the event where the user provides a "Country", a "Category" and/or a "Subcategory" but, although the database has entries for that country, it does not have entries for that country in that category or subcategory. 4-作为最后一种情况,我希望脚本对用户提供“国家/地区”,“类别”和/或“子类别”的事件做出反应,但是,尽管数据库具有该国家/地区的条目,但它没有在该类别或子类别中有该国家的条目。 In this case, I want the script to ask the user if it wants to see all information on the searched country, regardless of "Category" or "Subategory". 在这种情况下,我希望脚本询问用户是否要查看所搜索国家/地区的所有信息,而不管“类别”或“子类别”如何。 I tried to do this through an IfElse statement, part of the previous IF statement: 我试图通过IfElse语句(以前的IF语句的一部分)来做到这一点:

ElseIf Sheets("Database").Cells(i, 1) = country And _
       (Sheets("Database").Cells(i, 3) <> Category) Then
        Dim question As Integer
        question = MsgBox("Unfortunately, the Database has no sources regarding " & Category & " in " & country & ". Would you perhaps want to broaden your search and see all sources regarding " & country & "?", vbYesNo + vbQuestion, "No results for your search")
        Sheets("Results").Range("D6").ClearContents
        Sheets("Results").Range("D7").ClearContents
        MsgBox question
            If question = vbYes Then
              Close
              Call SearchButton_Click
              Exit Sub
            Else
              Sheets("Results").Range("D5").ClearContents
              Sheets("Results").Range("D6").ClearContents
              Sheets("Results").Range("D7").ClearContents
              Exit Sub
            End If

These are the four scenarios I want the script to account for as possible. 这些是我希望脚本考虑的四种情况。

The search and the script as a whole are running fine when only scenarios 1, 2 and 3 are in place. 仅在场景1、2和3到位时,搜索和脚本整体运行良好。 However, when I insert the script of the ElseIf statement in scenario 4, something goes wrong. 但是,当我在方案4中插入ElseIf语句的脚本时,出现了问题。 Although scenarios 1 and 2 keep on working, whenever I search for a country on which I know there are entries for "Category" and "Subcategory", the script prompts scenario 4 as if there were no matches for that "Country", "Category" and "Subcategory". 尽管方案1和2继续工作,但是每当我搜索一个我知道有“类别”和“子类别”条目的国家/地区时,脚本都会提示方案4,就好像该“国家/地区”,“类别”没有匹配项”和“子类别”。

I am not sure what I might be doing wrong or what the problem is with my ElseIf statement. 我不确定我可能做错了什么,或者ElseIf语句出了什么问题。


Whole Code 整个代码

Private Sub SearchButton_Click()

Dim country As String 'Search query category user-inputted
Dim Category As String 'Search query category user-inputted
Dim Subcategory As String 'Search query category user-inputted
Dim finalrow As Integer
Dim LastRowForTable As Long 'Last filled row in Results table
Dim i As Integer 'row counter
Dim ws As Worksheet

Set ws = Sheets("Database")

'Erase any entries from the Results sheet
Sheets("Results").Range("B10:J200000").ClearContents

'Define the user-inputed variables
country = Sheets("Results").Range("D5").Value
Category = Sheets("Results").Range("D6").Value
Subcategory = Sheets("Results").Range("D7").Value
finalrow = Sheets("Database").Range("A200000").End(xlUp).Row

'If statement for search    
With Worksheets("Database")
    Set c = .Range("A:A").Find(What:=country, After:=.Cells(1, 1), _
            LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
            SearchDirection:=xlNext, MatchCase:=False)
    If Not c Is Nothing Then
    Else
        MsgBox "Unfortunately, the database does not have any sources for information in " & country & ". Please search for sources in relating to another country."
        Sheets("Results").Range("D5").ClearContents
        Sheets("Results").Range("D6").ClearContents
        Sheets("Results").Range("D7").ClearContents
        Exit Sub
    End If
End With

'If the country field is left empty, there is no need to even run a search
If country = "" Then
    Sheets("Results").Range("B10:J200000").Clear
    MsgBox "You must select a country in order to search the database. Please do so in the drop-down list provided."
    Sheets("Results").Range("D5").ClearContents
    Sheets("Results").Range("D6").ClearContents
    Sheets("Results").Range("D7").ClearContents
    Exit Sub
End If

For i = 2 To finalrow

    'If the country field is filled in and there results from the search made
    If Sheets("Database").Cells(i, 1) = country And _
        (Sheets("Database").Cells(i, 3) = Category Or Category = "") And _
        (Sheets("Database").Cells(i, 4) = Subcategory Or Subcategory = "") Then

        'Copy the headers of the "Database" sheet
        With Sheets("Database")
            .Range("A1:I1").Copy
        End With
        Sheets("Results").Range("B10:J10").PasteSpecial

        'Copy the rows of the table that match the search query
        With Sheets("Database")
            .Range(.Cells(i, 1), .Cells(i, 9)).Copy
        End With
        Sheets("Results").Range("B20000").End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats

    ElseIf Sheets("Database").Cells(i, 1) = country And _
        (Sheets("Database").Cells(i, 3) <> Category) Then

        Dim question As Integer
        question = MsgBox("Unfortunately, the Database has no sources regarding " & Category & " in " & country & ". Would you perhaps want to broaden your search and see all sources regarding " & country & "?", vbYesNo + vbQuestion, "Empty Sheet")
        Sheets("Results").Range("D6").ClearContents
        Sheets("Results").Range("D7").ClearContents

        MsgBox question
        If question = vbYes Then
            Close
            Call SearchButton_Click
            Exit Sub
        Else
            Sheets("Results").Range("D5").ClearContents
            Sheets("Results").Range("D6").ClearContents
            Sheets("Results").Range("D7").ClearContents
            Exit Sub
        End If

    End If

Next i

'Hides search form
Me.Hide

'Toggle Results sheet
Sheets("Results").Activate

End Sub
Private Sub SearchButton_Click()

Dim country As String 'Search query category user-inputted
Dim Category As String 'Search query category user-inputted
Dim Subcategory As String 'Search query category user-inputted
Dim finalrow As Integer
Dim LastRowForTable As Long 'Last filled row in Results table
Dim i As Integer 'row counter
Dim ws As Worksheet

Set ws = Sheets("Database")

'Erase any entries from the Results sheet
Sheets("Results").Range("B10:J200000").ClearContents

'Define the user-inputed variables
country = Sheets("Results").Range("D5").Value
Category = Sheets("Results").Range("D6").Value
Subcategory = Sheets("Results").Range("D7").Value
finalrow = Sheets("Database").Range("A200000").End(xlUp).Row

'If statement for search    
With Worksheets("Database")
    Set c = .Range("A:A").Find(What:=country, After:=.Cells(1, 1), _
            LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
            SearchDirection:=xlNext, MatchCase:=False)
    If Not c Is Nothing Then
    Else
        MsgBox "Unfortunately, the database does not have any sources for information in " & country & ". Please search for sources in relating to another country."
        Sheets("Results").Range("D5").ClearContents
        Sheets("Results").Range("D6").ClearContents
        Sheets("Results").Range("D7").ClearContents
        Exit Sub
    End If
End With

'If the country field is left empty, there is no need to even run a search
If country = "" Then
    Sheets("Results").Range("B10:J200000").Clear
    MsgBox "You must select a country in order to search the database. Please do so in the drop-down list provided."
    Sheets("Results").Range("D5").ClearContents
    Sheets("Results").Range("D6").ClearContents
    Sheets("Results").Range("D7").ClearContents
    Exit Sub
End If

For i = 2 To finalrow

    'If the country field is filled in and there results from the search made
    If Sheets("Database").Cells(i, 1) = country And _
        (Sheets("Database").Cells(i, 3) = Category Or Category = "") And _
        (Sheets("Database").Cells(i, 4) = Subcategory Or Subcategory = "") Then

        'Copy the headers of the "Database" sheet
        With Sheets("Database")
            .Range("A1:I1").Copy
        End With
        Sheets("Results").Range("B10:J10").PasteSpecial

        'Copy the rows of the table that match the search query
        With Sheets("Database")
            .Range(.Cells(i, 1), .Cells(i, 9)).Copy
        End With
        Sheets("Results").Range("B20000").End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats

    ElseIf Sheets("Database").Cells(i, 1) = country And _
        (Sheets("Database").Cells(i, 3) <> Category) Then

        Dim question As Integer
        question = MsgBox("Unfortunately, the Database has no sources regarding " & Category & " in " & country & ". Would you perhaps want to broaden your search and see all sources regarding " & country & "?", vbYesNo + vbQuestion, "Empty Sheet")

        MsgBox question
        If question = vbYes Then
            Sheets("Results").Range("D6").ClearContents
            Sheets("Results").Range("D7").ClearContents
            Category = Sheets("Results").Range("D6").Value
            Subcategory = Sheets("Results").Range("D7").Value
            If Sheets("Database").Cells(i, 1) = country And _
                (Sheets("Database").Cells(i, 3) = Category Or Category = "") And _
                (Sheets("Database").Cells(i, 4) = Subcategory Or Subcategory = "") Then

                'Copy the headers of the "Database" sheet
                    With Sheets("Database")
                        .Range("A1:I1").Copy
                    End With
                    Sheets("Results").Range("B10:J10").PasteSpecial

                        'Copy the rows of the "Database" that match the search query
                    With Sheets("Database")
                        .Range(.Cells(i, 1), .Cells(i, 9)).Copy
                    End With
                    Sheets("Results").Range("B20000").End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats
            End If
        Else
            Sheets("Results").Range("D5").ClearContents
            Sheets("Results").Range("D6").ClearContents
            Sheets("Results").Range("D7").ClearContents
            Exit Sub
        End If

    End If

Next i

'Hides search form
Me.Hide

'Toggle Results sheet
Sheets("Results").Activate

End Sub

Ok what i did: 好的,我做了什么:

Stopped the end of sub and recalling. 停止了sub的结束并重新调用。

Stuck scenario 3 in the if msgbox=yes clause. 将方案3卡在if msgbox = yes子句中。 This of course requires that we reset category and subcategory to blank, which I also did. 当然,这要求我们将类别和子类别重置为空白,我也这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM