对象必需 – VBA Excel
挣扎着这个错误 – 我不太熟悉面向对象的编程,所以我可能只是搞乱语法或什么的。 我简化了我的代码,只显示了导致问题和相关variables的原因:
Type layer Step As Variant End Type Sub PullData() j = 6 Do While a <= j steps(1, a) = Sheets("Sheet2").Range("B" & a) a = a + 1 Loop a = 1 For a = 1 To j If steps(1, a) = 0 layer.Step = steps(1, a) 'From here there is a bunch of code where I use that value to copy a 'bunch of other values in the worksheet and paste into a different one, 'then move onto the next "item" in the array Next a End Sub
基本上我想要做的是从工作表中取一定范围的数据,将该范围转换为一维数组,然后通过每次迭代设置layer.Step
等于每个值。 错误发生在layer.Step = steps(1, a)
第二个循环中的layer.Step = steps(1, a)
。
那么,这里有一些你做错了的事情。 我将列出他们:
- 首先,
steps
是一个二维数组。 要声明一个一维数组,您不需要1
部分,只需声明它就像这样:Dim steps(n) As variant
- 在你的代码中,你启动了一个
If
条件,但是你没有完成它(可能原来的代码并不是这样)。 - 现在关于你的错误:你声明了一个用户定义types(
layer
),但你从来没有创build它的variables。 你不能只使用types名称。 你可以像这样创build一个typeslayer
的variables:Dim myLayer as layer
,然后你需要用layer.step = '..
replacelayer.step = '..
一个可以修改以适应您的需求的工作示例:
Type Layer Step As Variant End Type Sub PullData() Dim steps(7) As Variant Dim j As Integer: j = 6 Dim a As Integer: a = 1 Do While a <= j ' it's better here to use `For` loop instead. steps(a) = Sheet1.Range("B" & a) a = a + 1 Loop Dim myLayer As Layer For a = 1 To j myLayer.Step = steps(a) ' Rest of your code Next a End Sub
希望帮助:)