Userform在特定的WB上

时间:2015-11-06 14:47:10

标签: excel vba reference userform

我在特定的WorkBook上有一个userform,它的作用是从用户收集数据并将其转储到同一个WorkBook上。我的问题是,如果我将WB最小化并打开另一个WB并填写用户表单,则数据不会转储到最小化的工作簿上。我不确定如何引用该特定的WorkBook,这样即使其他WorkBook打开,它仍然会将我的数据转储到我想要的WorkBook上。这一切都可能吗?如果是这样,怎么样?

这是我的代码供参考。

Private Sub cmdSubmit_Click()

Application.ScreenUpdating = False
Application.DisplayAlerts = False

If ActiveWorkbook.MultiUserEditing Then
ActiveWorkbook.AcceptAllChanges
ActiveWorkbook.Save
End If

    If txtCallID.Value = "" Then
    MsgBox "Please enter a Call ID.", vbExclamation, "CALL ID FIELD ERROR"


'if all fields were answered, show Message Box for confirmation
    Else
        Dim response As Integer


        response = MsgBox("Please review all information before proceeding." & vbCrLf & "Click YES to Proceed, Click NO to review.", _
                vbYesNo + vbInformation, "Audit Tracker")

     End If
        If response = vbYes Then

    Dim lRow As Long
    Dim ws As Worksheet


    Set ws = Worksheets("Data Sheet")
    'find  first empty row in database
    lRow = ws.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row


    If WorksheetFunction.CountIf(ws.Range("E2", ws.Cells(lRow - 1, 1)), Me.txtCallID.Value) > 0 Then
        MsgBox "Somebody is already auditing this call", vbCritical, "Duplicate Call ID"
        Me.txtCallID.Value = ""
        Exit Sub
    End If



     'check for a segement id
    If Trim(Me.txtCallID.Value) = "" Then
        Me.txtCallID.SetFocus
        MsgBox "Please enter the Call ID"
        Exit Sub
    End If

     'copy the data to the database
     With ws
    .Cells(lRow, 1).Value = txtDate.Value
    .Cells(lRow, 3).Value = Environ$("username")
    .Cells(lRow, 5).Value = Me.txtCallID.Value


If ActiveWorkbook.MultiUserEditing Then
ActiveWorkbook.AcceptAllChanges
ActiveWorkbook.Save
End If

     'clear the data
    Me.txtCallID.Value = ""

    Me.txtCallID.SetFocus
   End With
   End If

Application.ScreenUpdating = True
Application.DisplayAlerts = True


End Sub

我希望做的是始终将数据转储到我的工作簿,即DataTracker.xlsd

1 个答案:

答案 0 :(得分:0)

  

这样即使其他WorkBook打开,它仍会将我的数据转储到我想要的WorkBook上

ThisWorkbook指的是拥有正在执行的表单或代码模块的工作簿。另一方面,ActiveWorkbook引用Excel中当前活动的工作簿,无论它是哪一个。修复你的代码:

ActiveWorkbook替换为ThisWorkbook

另外:Set ws = Worksheets("Data Sheet")

Set ws = ThisWorkbook.Worksheets("Data Sheet")

因为没有指定ThisWorkbook,没有限定符的Worksheets函数将获取ActiveWorkbook的工作表(默认行为),并且可能会失败。