范围types不匹配vba

在将范围值与""vbNullString进行比较时,出现types不匹配错误。 我阅读了许多类似的问题和解决这个问题的post。

数据全是数字或""

 Sub vegetableCounting() Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet Dim ws1Range As Excel.range, ws2Range As Excel.range, ws3Range As Excel.range, ws2Loop As Excel.range Dim ws1Row As Long, ws1Col As Long, ws2Row As Long, ws2Col As Long ' Dim rowCounter As Long, colCounter As Long, rowsMendo As Long Dim mendoSum As Double ' Set ws1 = Sheets("shareSchedule") Set ws2 = Sheets("shareDistribution") Set ws3 = Sheets("vegCount") '***not yet set to the full ranges*** Set ws1Range = ws1.range("E7:H11") 'shareSchedule Set ws2Range = ws2.range("D7:BB17") 'shareDistribution Set ws3Range = ws3.range("D7:BB11") 'vegetableCount '***not yet set to the full ranges*** rowsMendo = 0 rowCounter = 0 colCounter = 0 mendoSum = 0 For ws1Row = 0 To ws1Range.Rows.count Step 1 For ws1Col = 0 To ws1Range.Columns.count Step 1 If ws1Range.Offset(ws1Row, ws1Col).value <> "" Then For Each ws2Loop In ws2Range '11rows*51cols = 561 ws2Row = ws2Row + rowCounter + rowsMendo ws2Col = ws2Col + colCounter If ws2Range.Offset(ws2Row, ws2Col).value = "" Then Exit For Else If ws1Range.Offset(ws1Row, ws1Col).Interior.ColorIndex = 24 And _ ws2Range.Offset(ws2Row, ws2Col).Interior.ColorIndex = 24 Then 'a MENDO match If rowCounter < 3 Then mendoSum = mendoSum + ws1Range.Offset(ws1Row, ws1Col).value * ws2Range.Offset(ws2Col, ws2Row) rowCounter = rowCounter + 1 ElseIf rowCounter = 3 Then colCounter = colCounter + 1 rowCounter = 0 ElseIf colCounter = ws2Range.Columns.count + 1 And _ ws2Range.Offset(ws2Row, 1).Interior.ColorIndex = 24 And _ ws2Range.Offset(ws2Row + 4, 1).Interior.ColorIndex = 24 Then colCounter = 0 rowsMendo = rowsMendo + 3 ElseIf colCounter = ws2Range.Columns.count + 1 And _ ws2Range.Offset(ws2Row, 1).Interior.ColorIndex = xlNone And _ ws2Range.Offset(ws2Row + 4, 1).Interior.ColorIndex = xlNone Then colCounter = 0 rowsMendo = rowsMendo + 1 End If ws3Range.Offset(ws1Row, ws2Col) = ws1Range.Offset(ws1Row, ws1Col).value * ws2Range.Offset(ws2Row, ws2Col).value End If End If Next End If Next ws1Col Next ws1Row 'for ws2 'Offset(0, 0), Offset(1, 0), Offset(2, 0), then 'Offset(0, 1), Offset(1, 1), Offset(2, 1), then 'Offset(0, 2), Offset(1, 2), Offset(2, 2), then 'etc End Sub 

我得到的错误

  If ws1Range.Offset(ws1Row, ws1Col).value <> "" Then 

和不正确的概率再次得到它

 If ws2Range.Offset(ws2Row, ws2Col).value = "" Then 

有什么想法吗? 这里有一些工作表的图像,我试图从中拉出来

您可以尝试CStr将该值转换为一个string。 Format也可以使用,因为它处理NullCStr会产生一个错误。

所以:

If CStr(ws1Range.Offset(ws1Row, ws1Col).value) <> "" Then

要么

If Format(ws1Range.Offset(ws1Row, ws1Col).value) <> "" Then

我通常不使用Offset函数,但是可以通过像数组那样直接指定行和列来访问指定范围内的单元格。

EG:ws2Range(ws2Row,ws2Col).value

尽pipe你必须从1开始迭代,但是当你从0开始的时候你会得到一个错误。

当查看一个范围的偏移量时,将得到整个范围区域,并由您的偏移值进行偏移。

例如

 set a=sheets(1).range("A1:F40") debug.print a.offset(1,1).address 

结果

 $B$2:$G$41 

注意这是(A + 1,1 + 1:F + 1,40 + 1)而不是单个单元格

有2个选项:

  1. 将您的范围设置为单个单元格,并使用偏移来查看该单元格周围的区域
  2. 使用现在的范围,并使用cells(x,y)来查看该范围