【发布时间】:2020-07-23 22:59:56
【问题描述】:
我正在使用用户表单并有 2 个主要工作表。 1 (shE) 整理所选信息,2 (shL) 是所有可用选项的存储位置 - 这些是我的查找。
shL 在第 2 行有一个团队列表,每 4 列,在第 3 行,每个团队的属性列表。所以结构是 AB2 = Team1,AF2 = Team2,AJ2 = Team3。 AB3 = Attribute1,AC3 = Attribute2,AD3 = Attribute3,AE3 = Attribute4,AF3 = Attribute1 等等。
Dim shE, shL as Worksheet
Dim FoundTeam as range
Dim c, cc, y, mtc as long
Set shE = Sheets("EnteredData")
Set shL = Sheets("Lookups")
Set FoundTeam = shL.Range("AB2:BX2").Find(what:=shE.Range("D10"))
c = FoundTeam.Column
cc = c + 3
y = shL.Cells(shL.Rows.Count, c).End(xlUp).Row
' the next line of code causes the run-time error 1004 if shL is not the last-active worksheet
mtc = Application.Match(shE.Range("J3"), shL.Range(Cells(4, cc), Cells(y, cc)), 0)
shE.Range("Q3").Value = WorksheetFunction.Index(shL.Range(Cells(4, c), Cells(y, c)), mtc) 'this is actually part of a loop so the shE.Range("Q3") is more like ("Q" & i)
为了清楚起见,shE.Range("J3") 存储 Attribute4(用户可选择)(在每个团队的 shL 第 4 列中找到),shE.Range("D10") 是团队名称。
我遇到的问题是代码完美运行如果 shL 是 Excel 上的最后一个活动工作表。但是,如果最后一个活动工作表是 shE(或任何其他工作表),我将收到运行时错误 1004:对象“_Worksheet”的方法“范围”失败。
我不明白为什么这段代码只有在 shL 是最后激活的情况下才有效。这将被我组织中的几个不同的人使用,他们不会看到 shL。
我可以做些什么来修复运行时错误,或者有没有办法更好地查找/查找/提取信息?
【问题讨论】:
-
尝试完全限定所有范围。例如 Cells(... 应该是 SheetCodeName.Cells(...
-
在
VBA中,您必须单独声明所有变量。所以你的Dim c, cc, y, mtc as long转换为:mtc = Long并且这一行中的所有其他变量都是Variant类型。将其更改为:Dim c As Long, cc As Long, y As Long, mtc as long -
@RicardoDiaz - 我认为我的细胞已经完全合格。工作表由 Dim 中指定的 shL 标识。不过还是谢谢。
-
@Zac - 感谢您的反馈。我对此有一个挥之不去的怀疑,但很高兴得到证实。我现在已经修改了我的所有变量。它并没有对这段代码的功能产生一点盲目的影响,但至少我的变量被正确引用了。谢谢
-
@Marc 澄清一下,这不是完全合格的:
shL.Range(Cells(4, cc), Cells(y, cc))看到这个answer