如果找到匹配项,请更改单元格值

时间:2016-11-16 18:46:37

标签: excel vba

我有一个工作表,其中包含一个文本框,其中包含一个将分配给宏的按钮。在此工作簿中,有另一个工作表将主数据保存在表中。文本框将有一个作业#。我要做的是在主表中的作业#列(列B /命名范围:“JobCol_Master”)中查找作业#,如果找到匹配,则在该行中验证基于的值列D中的内容。如果为true,则更改该行中特定列的单元格值。

我在第Range(Cells(cell, 11)).Value = "Test"行遇到类型不匹配错误。当值不匹配时,我也会收到错误。

我感谢任何人都可以给我的任何指导。

Option Explicit

Sub IDCloseJob()

Dim ws As Worksheet
Dim MasterData As Range
Dim sourceID As Range
Dim cell As Range, row As Range, JobCol As Range
Dim Txt As String

Txt = ThisWorkbook.Worksheets("ID").TextBoxID.Text
Set MasterData = ThisWorkbook.Worksheets("Jobs").Range("MasterData")


If Txt <> "" Then
    With MasterData
        For Each cell In .Range("JobCol_Master")
            'If job# matches textbox and if job# has value equal to "ID" in Column D then...
            If cell.Text = Txt Then
              Cells(cell.row, 11).Value = "Test"
            Else
              MsgBox "Job# not found."
            End If
        Next cell
    End With
 End If

End Sub

更新代码:

Sub IDCloseJob()

Dim MasterData As Range
Dim sourceID As Range
Dim cell As Range, row As Range, JobCol As Range
Dim Txt As String

Txt = ThisWorkbook.Worksheets("ID").TextBoxID.Text
Set MasterData = ThisWorkbook.Worksheets("Jobs").Range("MasterData")


If Txt <> "" Then
    With MasterData
        For Each cell In .Range("JobCol_Master")
            'If job# matches textbox and if job# has value equal to "ID" in Column D then...
            If cell.Text = Txt Then
              Cells(cell.row, 11).Value = "Test"
            Else
              MsgBox "Job not found."
              Exit Sub
            End If
        Next cell
    End With
 End If
End Sub

如果为true,则上述代码不会完成真实语句Cells(cell.row, 11).Value = "Test"。它调出MsgBox然后退出子。不确定为什么...代码看起来正确。如果我遗漏了虚假陈述,那就完成了我的真实陈述。

1 个答案:

答案 0 :(得分:1)

更改

      Range(Cells(cell, 11)).Value = "Test"

      .Cells(cell.Row,11).Value = "Test"