【问题标题】:VBA can't get if, elseif, else statement to workVBA 无法使 if、elseif、else 语句正常工作
【发布时间】:2020-07-13 19:43:21
【问题描述】:

我正在尝试使用表单字段来检查表列值以预限定查询以运行这是我拥有的代码,但我遇到了运行时错误。

' Set Warnings
DoCmd.SetWarnings False
If Forms!FrmCopyRoutingMenu!TextTarget = tblQuoteSection1Lines!tblQuoteMstrID Then
    MsgBox ("Quote Section 1 Already Started! Please Copy Individual Sections.")

ElseIf Forms!FrmCopyRoutingMenu!TextTarget = Table!tblQuoteSection2Lines!tblQuoteMstrID Then
    MsgBox ("Quote Section 2 Already Started! Please Copy Individual Sections.")

ElseIf Forms!FrmCopyRoutingMenu!TextTarget = Table!tblQuoteSection3Lines!tblQuoteMstrID Then
    MsgBox ("Quote Section 3 Already Started! Please Copy Individual Sections.")

ElseIf Forms!FrmCopyRoutingMenu!TextTarget = Table!tblQuoteSection4Lines!tblQuoteMstrID Then
    MsgBox ("Quote Section 4 Already Started! Please Copy Individual Sections.")

ElseIf Forms!FrmCopyRoutingMenu!TextTarget = Table!tblQuoteSection5Lines!tblQuoteMstrID Then
    MsgBox ("Quote Section 5 Already Started! Please Copy Individual Sections.")

Else

【问题讨论】:

  • 欢迎来到 Stack Overflow。发布您遇到的问题的错误消息是明智的。这将使用户能够确定发生了什么。
  • 运行时错误 '424' 需要对象
  • 我认为您不能链接到这样的表格。您将不得不使用记录集对象打开表并以这种方式获取列。
  • 在不相关的说明中,您肯定不应该有 5 个表 tblQuoteSection1..5Lines,而是一个表 tblQuoteSectionLines 和一个部分列。这将使一切变得更容易。

标签: ms-access vba


【解决方案1】:

是否要检查 TextTarget 中的值是否在每个表的 ID 字段中的任何位置?这行得通吗?

Dim target As String
Dim Found As Boolean

target = Forms!FrmCopyRoutingMenu!TextTarget
Found = False

For i = 1 To 5
If DCount("tblQuoteMstrID", "tblQuoteSection" & i & "Lines", "tblQuoteMstrID = '" & target & "'") > 0 Then
    MsgBox ("Quote Section " & i & " Already Started! Please Copy Individual Sections.")
    Found = True
End If
Next i

If Not Found Then
    'code to run query goes here
End If

【讨论】:

  • 这看起来可能有效,但如果它不是真的,我无法将它转移到运行查询的 else 语句中。
  • @Corey 一种方法是包含一个可以在循环完成后检查的布尔值。我已经相应地编辑了我的答案
  • 感谢您对此的帮助,但我通过使用查询从每个表中创建所需主 ID 的单个表,然后我使用了 if (DAVG()>0) .再次感谢您对此提供的帮助,您的想法正是我从另一个方向开始看待问题所需要的。
  • 在技术方面,使用临时表来识别您要查找的 ID 确实有效,但如果您不小心,它很容易变成 Rube Goldberg 机器。像@Leroy 推荐的那样循环遍历您的数据集将是进行此操作的首选方式。
猜你喜欢
  • 1970-01-01
  • 2019-07-29
  • 2014-09-27
  • 2016-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多