将值分配给数组vba

时间:2018-03-30 11:53:21

标签: excel vba excel-vba

我没有在VBA中使用数组的经验而且我迷路了。我尝试做的是以下内容:

在A栏中我有~15个字符串(数字有时不固定,有时候更少)

我删除重复项,然后对于A列中的每个名称,我想在文件中创建单独的工作表。

我创建了一个数组,我尝试使用此循环从A中分配每个名称:

Sub assigningvalues()

Dim i As Integer
Dim myArray(20) As Variant
Dim finalrow As Long

ActiveSheet.Range("A1", Range("A1").End(xlDown)).RemoveDuplicates Columns:=Array(1)

finalrow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlDown).Row

'For i = 2 To finalrow -> I get overflow error when I use this range   
For i = 2 To Cells(20, 1)  
    myArray(i) = Cells(i, 1).Value    
Next i

'I check with the lines below if values were assigned    
Cells(2, 4).Value = myArray(4)
Cells(3, 4).Value = myArray(2)

End Sub

然而,来自单元格的值不会分配给数组

此外,当我尝试使用finalrow作为循环的范围时,我遇到溢出错误(这不是一个大问题,因为有解决方法,尽管知道我做错了会很好)

2 个答案:

答案 0 :(得分:3)

尝试以下代码:

Option Explicit

Sub assigningvalues()

Dim i As Long
Dim myArray(20) As Variant
Dim FinalRow As Long
Dim Sht As Worksheet

Set Sht = ThisWorkbook.Sheets("Sheet1") ' modify "Sheet1" to your sheet's name

With Sht
    .Range("A1", .Range("A1").End(xlDown)).RemoveDuplicates Columns:=Array(1)

    FinalRow = .Cells(.Rows.Count, "A").End(xlUp).Row ' get last row in column "A"

    For i = 2 To FinalRow
        myArray(i) = Cells(i, 1).Value
    Next i

    'I check with the lines below if values were assigned
    .Cells(2, 4).Value = myArray(4)
    .Cells(3, 4).Value = myArray(2)
End With

End Sub

注意:您可以使用Range在没有For循环的情况下将Application.Transpose的内容读取到1-D数组,您需要更改你定义它的行:

Dim myArray As Variant

并使用以下命令填充整个数组:

myArray = Application.Transpose(.Range("A2:A" & FinalRow))

答案 1 :(得分:0)

尝试以下代码:

    Sub assigningvalues()

    Dim myArray As Variant
    ActiveSheet.Range("A1", Range("A1").End(xlDown)).RemoveDuplicates Columns:=Array(1)

    myArray = ActiveSheet.Range("A1", Range("A1").End(xlDown))


    For Each element In myArray
        ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)).Name = element
    Next element

End Sub

注意:上述代码的问题是,

ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlDown).Row 

返回工作表中的绝对行数,而不是已使用的行数。由于你的数组长度为20,而工作表大约为1兆。行,你有溢出。您可以使用

进行检查
Debug.Print ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlDown).Row

在上面的代码中,删除dublicates之后,再次从A1向下移动到最后并将范围保存到数组中。数组myArray现在包含缩小范围内的所有单元格值。

现在用

循环元素
For Each element in myArray

并创建一个包含Workbook.Sheets.Add的新工作表,并为其设置名称Sheets(index).name = element

以上代码应该适合您。几句话:

而不是使用"ActiveSheet", ThisWorkbook, etc.你应该总是用这个开始一个Sub:

Dim wb As Workbook
Set wb = ThisWorkbook 'for the workbook containing the code
Set wb = Workbooks(workbookName) 'to reference an other Workbook

'And for all the sheets you are using
Dim ws As Worksheet
Set ws = wb.Sheets(sheetName) 'this way you avoid problems with multiple 
                               workbooks that are open and active or 
                               unactive sheets.