如何构造if else语句以检查组合框值是否在特定范围内

时间:2016-11-18 02:56:22

标签: excel-vba if-statement combobox vba excel

我有一个组合框列表,它由5个范围组成,每个范围来自不同工作簿的不同工作表。我想通过使用if else语句检查组合框值是否在一定范围内(检查其中的工作表),但我无法使代码生效:

Sub TextBox2_Change()

Dim value As String
    value = ComboBox1.value

Dim bdate As String
    bdate = Format(Now(), "mm/dd/yyyy")
Dim ddate As Date

Dim Found As range
Set Found = Workbooks("Library_Database.xlsx") _
            .Worksheets("Sheet1",  "Sheet2", "Sheet3") _                                  
            .Columns("A").Find(what:=value, LookIn:=xlValues)

If Found = Workbooks("Library_Database.xlsx").Worksheets("Sheet1") _
           .Columns("A").Find(what:=value, LookIn:=xlValues) Then
    ddate = DateAdd("m", 2, bdate)
ElseIf Found = Workbooks("Library_Database.xlsx").Worksheets("Sheet2") _ 
               .Columns("A").Find(what:=value, LookIn:=xlValues) Then
    ddate = DateAdd("h", 3, bdate)
ElseIf Found = Workbooks("Library_Database.xlsx").Worksheets("Sheet3") _    
               .Columns("A").Find(what:=value, LookIn:=xlValues) Then
    ddate = DateAdd("d", 2, bdate)
End If

Msgbox "" &ddate, vbinformation

End Sub

请帮助!!!!!

1 个答案:

答案 0 :(得分:0)

Range.Find不适用于多个工作表。

此语法具有误导性,因为日期值为数字:

bdate = Format(Now(), "mm/dd/yyyy")

最好使用DateValue函数代替:

bdate = DateValue(Now())

Sub TextBox2_Change()
    Dim ws As Worksheet
    Dim Found As Range
    Dim bdate As String
    Dim value As String
    value = ComboBox1.value
    bdate = DateValue(Now())
    Dim ddate As Date
    For Each ws In Workbooks("Library_Database.xlsx").Worksheets(Array("Sheet1", "Sheet2", "Sheet3"))
        Set Found = ws.Columns("A").Find(what:=value, LookIn:=xlValues)
        If Not Found Is Nothing Then
            Select Case ws.Name
            Case "Sheet1", "Sheet3"
                ddate = DateAdd("m", 2, bdate)
            Case "Sheet2"
                ddate = DateAdd("h", 3, bdate)
            End Select
            MsgBox "Date: " & ddate, vbInformation, "Date Found"
            Exit For
        End If
    Next

    If Found Is Nothing Then MsgBox "Try Again", vbCritical, "Date Not Found"

End Sub