如何使用动态变量?

How to use Dynamic Variables?

好的,我做错了什么?在网上找到这个,试了一下,发现类型不匹配。只是试图通过让变量定义自己来使我的代码更简洁,例如Y(10)、Y(11)、Y(12)、Y(13) 或 Y10 ... Y13,所以我将在子句末尾有 4 个变量。 Y10-13 不是单元格位置,但它们是相关的。往下看!

变量 a 指的是实际行,所以说 Y10 = 400 是第 5 行的唯一条目,第 7 行有 Y10 = 7 和 Y12 = 3。我没有在代码中定义它,因为这部分运行为function(a) 和 a 在函数本身之前定义,这样子检查 a=1 到最后一行。

Dim Y(10 To 13) As Integer 'these are just variables
Dim a as long 'this is an arbitrary row number defined before the function

For I = 10 to 13 'These are column numbers in the actual data range

If .Worksheets("15SK").Cells(a, I) <> "" Then
    Y(I) = .Worksheets("15SK").Cells(a, I).value 'Y(I) basically takes the value of the cell (a,I)
End If

Next

我基本上需要一个动态变量 Y(I) 或 YI(实际上是任何形式),因为我的代码的后面部分需要它。我将分享另一部分来陈述我的观点,但我很难翻译我在下一节中所做的事情:

For I = 10 To .Worksheets("15SK").Cells(2, Columns.Count).End(xlToLeft).Column 'All models

    If .Worksheets("15SK").Cells(a, I) <> "" Then 'If product model order > 0
    'removed a section of code here

        j = j + 3 'step 3
If ItemType = "Adaptor" And Y > X1 And DUP <> 1 Then

            Y1 = Y1 + Y(I)

                If ItemType = "Adaptor" And Y1 > X1 Then 'adding another duplicate

                    DOwb.Worksheets(1).Cells(j, 3) = .Worksheets("15SK").Cells(2, I) 'First DO product model row
                    DOwb.Worksheets(1).Cells(j - 1, 1) = Y1 - X1 'Excess Qty to be charged
                    DOwb.Worksheets(1).Cells(j - 3 - 1, 1) = Y(I) - (Y1 - X1) 'Making the previous row's Qty FOC by no. of CD - no. of previous
                    DOwb.Worksheets(1).Cells(j - 1, 2) = "pcs"
                    DOwb.Worksheets(1).Cells(j - 1, 3) = Application.WorksheetFunction.VLookup(DOwb.Worksheets(1).Cells(j, 3), .Worksheets("Catalogue").Range("catalogue"), 2, False) 'Model Description
                    JFOC = j
                    j = j + 3 'step 3
                    DUP = 1 'stops the duplication

                ElseIf Y1 = X1 Then
                    JFOC = j
                End If
            Y1 = 0
        End If

抱歉 VBA 或编码问题的新手。到目前为止帮助很大!

Y10 不能是变量名(因为它可能与单元格 Y10 混淆)。尝试使用此类变量名的代码将不起作用。尝试其他名称,例如 y_10 就可以了。