根据不同工作表上的匹配值更改值

时间:2016-11-16 21:30:28

标签: excel vba macros

此代码仅在我在主数据所在的工作表("作业")表上时才能正常工作。文本框和宏按钮位于工作表上(" ID")。当我在工作表(" ID")上运行代码时,我只收到MsgBox消息并且代码结束。当条件为真时,它不会更新值。有人可以查看代码,看看问题是什么?无法搞清楚这一点。

谢谢。

Option Explicit

Sub CloseJob()

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

On Error GoTo errHndl
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# is to correct region then...
            If cell.Text = Txt And Cells(cell.row, 4).Value = "ID" Then
              Cells(cell.row, 11).Value = "Test"
              Exit Sub
                If cell.Text <> Txt Then
                    Exit Sub
                End If
            End If
        Next cell
    End With
 End If

MsgBox "Job not found."

Exit Sub
errHndl:
    MsgBox "Error happened while working on: " + vbCrLf + _
        vbCrLf + vbCrLf + "Error " + _
        Str(Err.Number) + ": " + Err.Description, vbCritical + vbOKOnly, "Error"
End Sub

3 个答案:

答案 0 :(得分:3)

您的行For Each cell In .Range("JobCol_Master")正在尝试引用我认为不存在的MasterData范围的子范围。使用MasterData作为工作簿引用,或明确指定JobCol_Master。

答案 1 :(得分:3)

我猜你大部分都是在这段代码之后:

Option Explicit

Sub CloseJob()
    Dim cell As Range
    Dim Txt As String

    On Error GoTo errHndl

    With ThisWorkbook
        Txt = .Worksheets("ID").TextBoxID.Text
        If Txt <> "" Then
            With .Worksheets("Jobs")
                For Each cell In .Range("JobCol_Master")
                    'If job# matches textbox and if job# is to correct region then...
                    If cell.Text = Txt And .Cells(cell.row, 4).Value = "ID" Then
                        .Cells(cell.row, 11).Value = "Test"
                        Exit Sub '<-- remove it if you want to "mark" all job# matches in 'JobCol_Master' named range
                    End If
                Next cell
            End With
        End If
    End With
    MsgBox "Job not found."

    Exit Sub
errHndl:
        MsgBox "Error happened while working on: " + vbCrLf + _
            vbCrLf + vbCrLf + "Error " + _
            Str(Err.number) + ": " + Err.Description, vbCritical + vbOKOnly, "Error"
End Sub

虽然我不清楚宏按钮...在工作表(“ID”)上的作用。:如果该宏应该只通过该按钮调用,那么你的{ {1}}将永远是“ID”工作表

答案 2 :(得分:2)

同意上面的@atclaus,请更改为以下内容:

If Txt <> "" Then
    With sheets("Jobs")
        For Each cell In .Range("JobCol_Master")
            'If job# matches textbox and if job# is to correct region then...
            If cell.Text = Txt And Cells(cell.row, 4).Value = "ID" Then
              Cells(cell.row, 11).Value = "Test"
              Exit Sub
                If cell.Text <> Txt Then
                    Exit Sub
                End If
            End If
        Next cell
    End With
 End If

告诉我们您的情况:)