使用 WorksheetFunction 在嵌套循环中键入不匹配
Type Mismatch in nested loops with WorksheetFunction
Sub checkMe()
Dim lastRow As Long
Dim cell As Range
lastRow = Range("A" & Rows.Count).End(xlUp).Row
For Each cell In Range("B1:B" & lastRow) 'dynamically go through each row in the range
For a_counter = 2001 To 2015 ' for each row, cycle through each year until 2015
j = a_counter
b = cell.offset(0, 6).Value 'value for vlookup
a = Application.VLookup(b, Sheet2.Range("A2:N42"), (j - 2000 + 2), False) ' look up each value in offset(0,6) in another sheet
If cell.Value = "DUB" And cell.offset(0, 1).Value <= "2001" And cell.offset(0, 2).Value = "OSLR" Then cell.offset(0, j + 12 - 2000).Value = cell.offset(0, 7).Value * a 'only apply when the conditions are met
Next a_counter
Next
End Sub
顺序应该稍微改变一下,以便条件在内部循环之前以帮助加快速度,但除此之外我认为这应该可行。 cell.offset(0,6) 的值是我需要为 vlookup 查找每一行的值。如果我在 'b' 所在的位置输入一个值,则此代码有效,但是我需要查找该值以随每一行更改。目前它只适用于第一行并停止。现在我收到不匹配错误。
让我们做一些数学运算。
For a_counter = 2001 To 2015
a_counter 将对 15 个值进行排序;例如2001 ► 2015 年(含)。
Sheet2.Range("A2:N42")
共14列;例如A 列 ► N 列(含)。
j = a_counter
..., (j - 2000 + 2), ...
您正在从 3 ► 17 的 15 个不同列中请求 returns。
但是 A:N 有 14 列,所以当 a_counter = 2013 时会出错(类型不匹配),因为没有 15[=25=第 ] 列。
Sub checkMe()
Dim lastRow As Long
Dim cell As Range
lastRow = Range("A" & Rows.Count).End(xlUp).Row
For Each cell In Range("B1:B" & lastRow) 'dynamically go through each row in the range
For a_counter = 2001 To 2015 ' for each row, cycle through each year until 2015
j = a_counter
b = cell.offset(0, 6).Value 'value for vlookup
a = Application.VLookup(b, Sheet2.Range("A2:N42"), (j - 2000 + 2), False) ' look up each value in offset(0,6) in another sheet
If cell.Value = "DUB" And cell.offset(0, 1).Value <= "2001" And cell.offset(0, 2).Value = "OSLR" Then cell.offset(0, j + 12 - 2000).Value = cell.offset(0, 7).Value * a 'only apply when the conditions are met
Next a_counter
Next
End Sub
顺序应该稍微改变一下,以便条件在内部循环之前以帮助加快速度,但除此之外我认为这应该可行。 cell.offset(0,6) 的值是我需要为 vlookup 查找每一行的值。如果我在 'b' 所在的位置输入一个值,则此代码有效,但是我需要查找该值以随每一行更改。目前它只适用于第一行并停止。现在我收到不匹配错误。
让我们做一些数学运算。
For a_counter = 2001 To 2015
a_counter 将对 15 个值进行排序;例如2001 ► 2015 年(含)。
Sheet2.Range("A2:N42")
共14列;例如A 列 ► N 列(含)。
j = a_counter
..., (j - 2000 + 2), ...
您正在从 3 ► 17 的 15 个不同列中请求 returns。
但是 A:N 有 14 列,所以当 a_counter = 2013 时会出错(类型不匹配),因为没有 15[=25=第 ] 列。