如何使用动态变量?

时间:2015-06-11 07:35:19

标签: excel-vba variables dynamic vba excel

好吧,我做错了什么?在网上找到这个,试过它并得到类型不匹配。只是尝试通过让变量定义自己来使我的代码更简洁,例如Y(10),Y(11),Y(12),Y(13)或Y10 ... Y13,因此I< ll“在sub的末尾有4个变量。 Y10-13不是细胞位置,但它们是相关的。看下面!

the Actual Dataset

变量a指的是实际行,所以说Y10 = 400是第5行的唯一条目,第7行有Y10 = 7和Y12 = 3.我没有在代码中定义这个,因为这部分作为函数运行( a)和a在函数本身之前定义,以便sub检查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来说真的很新,或者为此事编码。到目前为止提供了极好的帮助!

1 个答案:

答案 0 :(得分:0)

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