将列分配给数组VBA

时间:2017-06-12 18:34:14

标签: vba excel-vba excel

我有这个代码。 DataSet被设置为变体。

DataSet = Selection.Value

工作正常,但有没有办法可以将其更改为A列,特别是A2到A502?我已经尝试将其设置为范围,但它不起作用。它还需要忽略空格,因为并非所有单元格都有内容。我试图消除突出细胞的需要,因为条目只会在特定范围内。

2 个答案:

答案 0 :(得分:1)

试试这两个版本:

Option Explicit

Public Sub getNonemptyCol_ForLoop()
    Dim dataSet As Variant, fullCol As Variant, i As Long, j As Long
    Dim lrFull As Long, lrData As Long, colRng As Range

    Set colRng = ThisWorkbook.Worksheets(1).Range("A2:A502")
    fullCol = colRng
    lrFull = UBound(fullCol)
    lrData = lrFull - colRng.SpecialCells(xlCellTypeBlanks).Count
    ReDim dataSet(1 To lrData, 1 To 1)

    j = 1
    For i = 1 To lrFull
        If Len(fullCol(i, 1)) > 0 Then
            dataSet(j, 1) = fullCol(i, 1)
            j = j + 1
        End If
    Next
End Sub
Public Sub getNonemptyCol_CopyPaste()   'without using a For loop
    Dim dataSet As Variant, ws As Worksheet

    Application.ScreenUpdating = False
    Set ws = ThisWorkbook.Worksheets(1)
    With ws.UsedRange
        ws.Activate
        .Range("A2:A502").SpecialCells(xlCellTypeConstants).Copy
        .Cells(1, (.Columns.Count + 1)).Activate
        ActiveSheet.Paste

        dataSet = ws.Columns(.Columns.Count + 1).SpecialCells(xlCellTypeConstants)
        'dataSet now contains all non-blank values

        ws.Columns(.Columns.Count + 1).EntireColumn.Delete
        .Cells(1, 1).Activate
    End With
    Application.ScreenUpdating = True
End Sub

答案 1 :(得分:0)

使用动态列进行分配。

Sub SetActiveColunmInArray()
    Dim w As Worksheet
    Dim vArray As Variant
    Dim uCol As Long
    Dim address As String


    Set w = Plan1 'or Sheets("Plan1") or Sheets("your plan name")
    w.Select
    uCol = w.UsedRange.Columns.Count
    address = w.Range(Cells(1, 1), Cells(1, uCol)).Cells.address

    vArray = Range(address).Value2

End Sub