编译错误:对象需要 VBA

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11355911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 16:46:03  来源:igfitidea点击:

Compile Error: Object Required VBA

excel-vbavbaexcel

提问by user1505743

I'm new to VBA. I'm trying to write a script that cleans up some data from an experiment. I keep getting an error saying "Object Required" and it highlights pold. Does anyone have any idea why?

我是 VBA 的新手。我正在尝试编写一个脚本来清理实验中的一些数据。我不断收到一条错误消息,指出“需要对象”,它突出显示了 pold。有谁知道为什么?

As for the script, I'm trying to go down a column of participant numbers and map out what range each participant is in. There are around 30 lines per participant, and I want to define that as values in an array.

至于脚本,我试图向下列出一列参与者编号并绘制出每个参与者所处的范围。每个参与者大约有 30 行,我想将其定义为数组中的值。

Sub Cleanthismofoup() 
Dim pranges(1 To 50) As Long 
Dim pbegin As Range
Dim pend As Range
Dim pold As Integer
Dim pnew As Integer
Dim pcell As Range
Dim pcounter As Long
Dim i As Long

Set pcell = Range("A1:A1")
Set pbegin = Range("A2:A2")
Set pold = Range("B2:B2").Value
pcounter = 0

'for every item, store value in pnew
' move down one line. Check pnew = pold
' if it is, do again. else create new range

For i = 1 To rngl
pcell = pcell.Offset(-1, 0)
pnew = pcell.Cells.Value
If pnnew <> pold Then pcell = pend
If pcell = pend Then
counter = counter + 1
pranges(counter) = pbegin
counter = counter + 1
pranges(counter) = pend
pbegin = pcell.Offset(-1, 0)
Else: pold = pnew
End If

i = i + 1
Next

End Sub

结束子

回答by hardikudeshi

The error is because you are using a Setkeyword which is used to assign reference to the object. Since the output on the RHS of Set pold = Range("B2:B2").Valueis an Integer, vba gives you an error. To resolve it simply remove the Setkeyword. However I also noticed that you are using rng1in the forloop without initializing the rng1variable, in which case your forloop will never execute. You might also want to rectify that.

错误是因为您使用了Set用于分配对象引用的关键字。由于 的 RHS 上的输出Set pold = Range("B2:B2").Value是整数,因此 vba 会给您一个错误。要解决它,只需删除Set关键字。但是我也注意到你rng1for循环中使用而不初始化rng1变量,在这种情况下你的for循环永远不会执行。您可能还想纠正这一点。