【发布时间】:2019-11-15 09:32:14
【问题描述】:
我对 VBA 非常陌生,并且一直在努力编写用户表单的代码,该用户表单需要在添加表格之前检查输入值以避免重复并在消息框中提供方向。
当用户单击“转移”命令按钮时,我希望代码首先查看用户尝试输入的 WONumber,看看是否已经在桌子上。如果 WONumber 不在表格中,则会出现一个消息框,告诉用户 WONumber 不存在。
如果 WONumber 在表上,我希望代码在所有 WONumber 与其输入匹配的情况下查看 SubName,并查看他们尝试输入的 SubName 是否已经存在于具有关联 WONumber 的表上。如果 SubName 已经在带有 WONumber 的表上,则会出现一个 msgbox,让用户知道 SubName 已经在 WONumber 上。如果 SubName 在表上但与用户输入的 WONumber 不同,则将具有关联 WONumber 的 SubName 添加到表中。本质上,WONumber 是表唯一的,SubName 是 WONumber 唯一的,但不是表唯一的。 (用户应该能够添加 SubName = "Smith" 与 WONumber = "5" 和 SubName = "Smith" 与 WONumber = "500" 但不应该能够添加 SubName = "Smith" 与 WONumber = "5" 两次。 )
我已经尝试过 If Not Nothing 的多种组合,因为我读到有时从那个方向工作会更容易。
我一般对 VBA 的经验很少,所以我不知道 .Find 是返回一个值还是一个位置,所以我编写的 ElseIf 条件可能根本没有意义,因为代码可能正在寻找一个位置和我要求它匹配文本。
我已尝试将 FoundWO.Value = PsblWOMatch.Value 和 FoundSub.Value = FoundSubName.Value 作为 Elseif 条件以及 .text。
我不确定 FoundWO 作为 Range,FoundSub 作为 Range,因为这似乎暗示 FoundWO 将是一组值,并且将一组数字与一个 PsblWOMatch 等同起来真的没有意义。
我还发现了一些关于特定错误代码 91 的 YouTube 视频,这与我的代码有关,不包括作为工作表的 dim ws 是问题,但是当我尝试更正它以匹配示例时,我得到了相同的结果错误代码只是在不同的行上。
Private Sub cmdTransfer_Click()
Dim FoundWO As Range
Dim PsblWOMatch As String
PsblWOMatch = txtWONumber.Text
Dim FoundSub As Range
Dim PsblSubMatch As String
PsblSubMatch = txtSubName.Text
Dim eRow As Long
eRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Set FoundWO = ActiveSheet.ListObjects("TableWO").ListColumns(1).DataBodyRange.Find(What:=PsblWOMatch, LookIn:=xlValues, Lookat:=xlWhole)
Set FoundSub = ActiveSheet.ListObjects("TableWO").ListColumns(2).DataBodyRange.Find(What:=PsblSubMatch, LookIn:=xlValues, Lookat:=xlWhole)
'If Condition 1 then
If FoundWO Is Nothing Then
'Code to execute
MsgBox "Work Order does not exist. Please add Work Order before adding subcontractors."
'If Condition 2 then
ElseIf FoundWO = PsblWOMatch And FoundSub = PsblSubMatch Then
'Code to execute
MsgBox "SubContractor has already been added to Work Order."
Else
'Code to execute
Cells(eRow, 1).Value = txtWONumber.Text
Cells(eRow, 2).Value = ""
Cells(eRow, 3).Value = txtSubName.Text
Cells(eRow, 4).Value = txtsubLocation.Text
End If
txtWONumber.Text = ""
txtSubName.Text = ""
txtsubLocation = ""
txtWONumber.SetFocus
End Sub
我已经能够让 msgbox 出现,告诉用户 WONumber 不存在。当 WONumber 确实存在时,我已经能够添加一个 SubName。但我收到运行时错误“91”:对象变量或未设置块变量。调试亮点位于 ElseIf 行。
【问题讨论】:
标签: excel vba if-statement userform