如果包含查找

时间:2016-01-22 13:40:34

标签: excel vba excel-vba

我正在向数据库添加信息。在这样做时,我想检查数据库中是否已存在该信息,因此我不会双重写入它。

Private Sub changebutton_dp_Click()
Dim sheet As Worksheet
Dim table_list_obj As ListObject
Dim table_obj_row As ListRow
Set sheet = Sheets("Database")
Set table_list_obj = sheet.ListObjects(1)
Set table_obj_row = table_list_obj.ListRows.Add

For Each sheet In ActiveWorkbook.Worksheets("Database")
   sheet.Cells.Find What:=DatabasePage.termaccepted_dp.Value,_
   LookIn:=xlValues, LookAt:=xlWhole 
   If sheet.Cells.Find.Range Is Nothing Then
       DatabasePage.yesno_dp.Caption = No
   ElseIf IsEmpty(sheet.Cells.Find.Range) Then
       DatabasePage.yesno_dp.Caption = No
   ElseIf sheet.Cells.Find.Range = "" Then
       DatabasePage.yesno_dp.Caption = No
   Else
       DatabasePage.yesno_dp.Caption = Yes
       DatabasePage.display_dp.Value = sheet.Cells.Find.Value
   End If
Next sheet

table_obj_row.Range(1, 1).Value = DatabasePage.termdenied_dp.Value

last_row = sheet.Range("A65536").End(xlUp).Row
last_row = last_row

sheet.Range("B" & last_row) = DatabasePage.termaccepted_dp.Value

End Sub

这会给出几个标志。

2 个答案:

答案 0 :(得分:0)

我无法对此进行测试,但您无法在一张纸上循环显示工作表,并且需要将Find操作的结果存储在Range变量中:

Private Sub changebutton_dp_Click()
    Dim sheet                 As Worksheet
    Dim table_list_obj        As ListObject
    Dim table_obj_row         As ListRow
    Dim rgFound               As Range

    Set sheet = Sheets("Database")

    Set table_list_obj = sheet.ListObjects(1)
    Set table_obj_row = table_list_obj.ListRows.Add

    Set rgFound = sheet.Cells.Find(What:=DatabasePage.termaccepted_dp.Value, _
                                   LookIn:=xlValues, LookAt:=xlWhole)
    If rgFound Is Nothing Then
        DatabasePage.yesno_dp.Caption = No
    ElseIf Len(rgFound.Value) = 0 Then
        DatabasePage.yesno_dp.Caption = No
    Else
        DatabasePage.yesno_dp.Caption = Yes
        DatabasePage.display_dp.Value = rgFound.Value
    End If


    table_obj_row.Range(1, 1).Value = DatabasePage.termdenied_dp.Value

    last_row = sheet.Range("A65536").End(xlUp).Row

    sheet.Range("B" & last_row) = DatabasePage.termaccepted_dp.Value

End Sub

答案 1 :(得分:0)

据我所知,唯一真正的问题是你的For each worksheet循环。您的代码有一些不正确的语法,并且您有多余的ElseIf条件。

请参阅下面的代码。 注意 - 我认为DatabasePage的内容是正确的,因为我现在还不确切知道它是什么。

For Each sheet In ActiveWorkbook.Worksheets 'assuming you want to loop through all sheets

    Dim rng As Range

    Set rng = sheet.Cells.Find(What:=DatabasePage.termaccepted_dp.Value, _
        LookIn:=xlValues, LookAt:=xlWhole)

    If rng Is Nothing Then
        DatabasePage.yesno_dp.Caption = No
    Else
        DatabasePage.yesno_dp.Caption = Yes
        DatabasePage.display_dp.Value = rng.Value
    End If

Next sheet

此代码将Find操作的值存储到Range对象中,然后测试对象是否具有值或为Null。