VBA使用Cells()循环选定的列

时间:2017-09-11 08:45:20

标签: arrays vba loops

假设我有一个包含15列和20行的电子表格。我想只用两列(比如第二和第十列)和所有行创建一个数组。我怎么能这样做?

我想这可能是一个很好的起点,但我不知道如何使用Cells()函数定义我选择的列。

Dim array1(20, 2) As Single
Set arrays = Sheets("Sheet1")

For i = 1 To 20
For j = 1 To 2
My_array(i - 1, j - 1) = arrays.Cells(i, j - ??)

2 个答案:

答案 0 :(得分:1)

如果我理解你,你想生成包含两个工作表列的所有数据的二维数组。我会用自定义函数做这样的事情:

' -----------------------------------------------------------------
' GetMyData - picks data from sheet's first 20 rows and two columns
'    - sheetName {String} - then name of the sheet where the data is taken
'    - col1 {Integer} - first column to read from
'    - col2 {Integer} - second column to read from
' returns: 2-dimensional array containing data of columns from the parameters
Function GetMyData(sheetName As String, col1 As Integer, col2 As Integer) As Variant
    ' declarations
    Dim sheet As Worksheet: Set sheet = ActiveWorkbook.Sheets(sheetName)
    Dim result(20, 2) As Variant

    ' logic
    Dim row As Integer, col As Integer
    For row = 1 To 20
        result(row - 1, 0) = sheet.Cells(row, col1)
        result(row - 1, 1) = sheet.Cells(row, col2)
    Next

    ' return the result
    GetMyData = result
End Function

你可以这样使用它:

Private Sub CommandButton1_Click()
    ' get data from Sheet3 first 20 rows columns 2(B) and 10(J)
    Data = GetMyData("Sheet3", 2, 10)
End Sub

现在关于这个函数的几句话 - 因为我们知道我们想要从两个列中获取数据,我们可以在一个循环中完成它并在这里完成所有工作:

For row = 1 To 20
    result(row - 1, 0) = sheet.Cells(row, col1) ' Take data from col1
    result(row - 1, 1) = sheet.Cells(row, col2) ' Take data from col2
Next

答案 1 :(得分:0)

Dim array1(20, 2) As Single
Set arrays = Sheets("Sheet1")

For i = 1 To 20
    For j = 1 To 2
        My_array(i - 1, j - 1) = arrays.Cells(i, j)

这应该这样做