Array返回空数据

时间:2014-08-05 10:23:36

标签: arrays excel-vba excel-2013 vba excel

我有这种非常奇怪的情况。代码在前一个sub中工作,但在另一个sub中它什么都不做。我挖得更深,发现阵列似乎是空的。这怎么可能:

Sub Knop1_Klikken()
Dim cbm_cnt, cbm_xnt, cbm_c, cbm_r As Integer
cbm_xnt = 1
cbm_cnt = 0
cbm_r = 1
cbm_c = 1
Dim cbm_Arr() As Variant ' declare an unallocated array.
Worksheets("Cbm").Activate

cbm_lrow = Worksheets("totallist").Cells.SpecialCells(xlCellTypeLastCell).Row
cbm_lcol = Worksheets("totallist").Cells(1, Columns.Count).End(xlToLeft).Column

cbm_Arr = Range(Sheets("totallist").Cells(1, 1).Address, Sheets("totallist").Cells(cbm_lrow, cbm_lcol).Address)

For cbm_r = 1 To UBound(cbm_Arr, 1) ' First array dimension is rows.
    For cbm_c = 1 To UBound(cbm_Arr, 2) ' Second array dimension is columns.
        If Worksheets("totallist").Cells(cbm_r, 9).Value = "Cbm" Then
            cbm_cnt = cbm_cnt + 1
            If cbm_cnt = 10 Then
                 cbm_xnt = cbm_xnt + 1
                 cbm_cnt = 1
            End If
            Worksheets("Cbm").Cells(cbm_xnt, cbm_cnt).Value = cbm_Arr(cbm_r, cbm_c)
            Worksheets("Cbm").Cells(cbm_xnt, 7).Value = ""
        End If

    Next cbm_c
Next cbm_r
End Sub

代码中cbm_Arr(cbm_r, cbm_c)似乎是空的。

代码假设要做什么: 在名为" totallist "的工作表中我正在寻找一个列-I代码cbm。如果找到此代码,则会将该行复制到名为" cbm "的另一个工作表中。我究竟做错了什么?

添加:当我这样做时

Worksheets("Cbm").Cells(cbm_xnt, cbm_cnt).Value = "x"

然后我的列获得" x"在细胞中。数组没有显示......

注意:cbm_lrow = 511和cbm_lcol = 9

1 个答案:

答案 0 :(得分:2)

您使用的Range功能适用于有效工作表,而不适用于您的totallist工作表。您需要使用完整工作表名称:

With Sheets("totallist")
    cbm_arr = .Range(.Cells(1, 1).Address, .Cells(cbm_lrow, cbm_lcol).Address).Value
End With

cbm_Arr = Sheets("totallist").Range(Sheets("totallist").Cells(1, 1).Address, Sheets("totallist").Cells(cbm_lrow, cbm_lcol).Address).Value