【发布时间】:2018-04-09 17:30:26
【问题描述】:
我正在尝试让 Sub 工作,它执行以下操作:
在 F 列中搜索包含单词“Total”的单元格
将找到的第一个“Total”实例的相邻单元格中的值写入数组
- 继续在 F 列中查找“Total”并将相邻值写入数组
- 在 Sheet2 的第二列中打印数组的值,每个值之间没有空白单元格。
到目前为止我所拥有的是:
Sub MatrixFill()
Dim I as Integer, lrow as Long, rng as Range, cell as Range, size as Integer
'Find # of cells in column F that have "Total" to size the array'
size = Application.WorksheetFunction.CountIf(Range("F1:F9999"), "Total")
'Resize the array to the amount of cells that contained "Total"'
ReDim arrVal(1 to size) as Long
lrow = Cells(Cells.Rows.Count, "F").End(xlUp).Row
Set rng = Range (F1:F9999" & lrow)
'Select the cell adjacent to each cell in the F column which contains "Total" and write to the array"
For Each cell In rng
If InStr(1, cell.Value, "Total", vbTextCompare) > 0 Then
ActiveCell.Offset(1,0).Select
arrVal(I) = ActiveCell.Value
End If
Next Cell
'Write the values from the array to the second sheet in the workbook in column B'
Sheets("Sheet2").Select
For i = LBound(arrVal) To UBound(arrVal)
Cells(2, 0+i).Select
Debug.Print i, arrVal(i)
Next i
End Sub
【问题讨论】:
-
lrow = Cells(Cells.Rows.Count, "F").End(xlUp).Row必须是lrow = Cells(Rows.Count, "F").End(xlUp).Row,而Set rng = Range (F1:F9999" & lrow)您打算使用Set rng = Range("F1:F" & lrow) -
@ShaiRado,感谢您的有用评论。我已将您提到的更改合并到代码中。但是,我在“arrVal(i)=ActiveCell.Value”行收到运行时错误 9。这一行是我尝试将单元格中的值分配给数组的地方。