我循环遍历一行单元格并尝试将这些单元格中的值分配给数组,但这会导致类型不匹配错误。我的代码的相关部分如下:
Dim queryaddress As Range
Dim notoffsetnum As Integer
Dim anotherarrayofnumbers() As Integer
Dim c As Range
For Each queryaddress In worksheetname.Range("B2:B21")
Set queryrow = queryaddress.EntireRow
notoffsetnum = 0
For Each c In queryrow
If c.Interior.Color <> 192 And Not IsEmpty(c.Value) Then
notoffsetnum = notoffsetnum + 1
ReDim Preserve anotherarrayofnumbers(notoffsetnum)
anotherarrayofnumbers(notoffsetnum) = c.Value
'The above line errors
End If
Next c
Next queryaddress
答案 0 :(得分:2)
for each
循环遍历集合。您有一个名为查询行的范围。你有一个名为c的范围。你所做的是遍历queryrow中的每个RANGE ...这意味着c只是查询行。
你想要
for each c in queryrow.cells
另外,请注意尽可能低效,因为它会遍历所有65000左右的列,而不是实际拥有数据的相对较少的列。
编辑:我不确定为什么这仍然会给你一个错误。但是你有其他逻辑错误。如果我从B2:H21中输入一些数据,这对我来说(也是为了爱的善意,缩进!),例如:Sub test()
Dim worksheetname As Worksheet
Set worksheetname = ActiveWorkbook.ActiveSheet
Dim queryaddress As Range
Dim notoffsetnum As Integer
Dim anotherarrayofnumbers() As Integer
Dim c As Range
For Each queryaddress In worksheetname.Range("B2:B21")
Dim queryrow As Range
Set queryrow = queryaddress.EntireRow
notoffsetnum = 0
For Each c In queryrow.Cells
If c.Interior.Color <> 192 And Not IsEmpty(c.Value) Then
notoffsetnum = notoffsetnum + 1
ReDim Preserve anotherarrayofnumbers(notoffsetnum)
anotherarrayofnumbers(notoffsetnum - 1) = c.Value
End If
Next c
Next queryaddress
Dim i As Integer
For i = 0 To UBound(anotherarrayofnumbers) - 1
Debug.Print anotherarrayofnumbers(i)
Next i
End Sub
另一个易于修复的问题是默认情况下,VBA数组是基于0的。它们从0开始,你错误地从1开始.VBA不会抛出错误,它只是将元素0设为0。
你真正的问题是,在每一行之后,你会淘汰旧数组,因为notoffsetnum会回到0,然后你将数组重新调整为大小为1.这会抛弃所有内容,最后你会反感出来。我刚刚排在最后一排。我认为这是一个错误。由于这是一个很大的问题,我认为这里有点清洁,而且不那么脆弱。我做的唯一假设是你从B2开始,并且你有数据向下和向右。如果这将成为一个问题,你可以稍微改变一下。我只是认为你会发现range.end(xl ...)方法是救生员。如果您按下ctrl +箭头键,它会将您带到的单元格,这样就可以快速找出范围的边缘。
Sub BetterSolution()
Dim ws As Worksheet
Set ws = ActiveWorkbook.ActiveSheet
Dim firstCell As Range
Set firstCell = ws.Range("B2")
Dim lastCol As Integer
lastCol = firstCell.End(xlToRight).Column
Dim lastRow As Integer
lastRow = firstCell.End(xlDown).Row
Dim lastCell As Range
Set lastCell = ws.Cells(lastRow, lastCol)
Dim arr() As Integer
Dim rng As Range
Dim index As Integer
index = 0
For Each rng In ws.Range(firstCell, lastCell).Cells
index = index + 1
ReDim Preserve arr(index + 1)
arr(index) = rng.Value
Next rng
End Sub
答案 1 :(得分:0)
我的代码中有问题的是:
Dim anotherarrayofnumbers() As Integer
导致错误:
anotherarrayofnumbers(notoffsetnum) = c.Value
这是因为我的一些c.Value
值实际上并不是整数。
解决此问题的一种方法是将数组更改为Variant类型:
Dim anotherarrayofnumbers() As Variant
但是这对我来说不起作用,因为我后来不得不在数组上执行整数运算(例如WorksheetFunction.Quartile
)。相反,我只是将格式应用于那些不是整数值的c.Value
值,以便将它们从我的数组中过滤掉。这解决了我的问题。
所以我对If
块的条件现在看起来像这样:
If c.Interior.Color <> 192 And c.Interior.Color <> 177 And Not IsEmpty(c.Value) Then
其他内部颜色是我将非整数值格式化为。