我在为VLOOKUP设置适当的动态范围时遇到问题,每次循环应增加58(我有96个不同的范围)。 VLOOKUP表在其他(“Gefco”)表中。我得到的错误是:
应用程序定义或对象定义的错误
代码:
Sub vlookup_rates()
Dim a As Long
Dim b As Long
Dim c As Long
Dim d As Long
Dim e As Long
Dim rr, dupa As Range
Dim ws, wws As Worksheet
Dim wb As Workbook
c = 1
a = 2
b = 59
d = 2
e = 59
Set wb = ActiveWorkbook
Set ws = wb.Sheets("Gefco")
With ws
Set rr = Range(Cells(d, 4), Cells(e, 8))
End With
Set wws = wb.Sheets("Waberers")
wws.Activate
Do While c < 97
Cells(4, a).Select
Cells(4, a).Formula = "=VLOOKUP($A$4;" & rr.Address & ";5;0)" <-ERROR
c = c + 1
a = a + 1
b = b + 1
d = d + 58
e = e + 58
Loop
End Sub
我认为范围在某种程度上是错误的定义,但我不能破解它。 请停下来。
谢谢!
答案 0 :(得分:1)
以下是你做错的一些事情:
Dim a As Long
Dim b As Long
Dim c As Long
Dim d As Long
Dim e As Long
Dim rr, dupa As Range '// rr will be dimensioned as variant
Dim ws, wws As Worksheet '// ws will be dimensioned as variant
Dim wb As Workbook
c = 1
a = 2
b = 59
d = 2
e = 59
Set wb = ActiveWorkbook
Set ws = wb.Sheets("Gefco")
With ws
Set rr = Range(Cells(d, 4), Cells(e, 8)) '// This range refers to the ActiveSheet, not the 'ws' object.
End With
Set wws = wb.Sheets("Waberers")
wws.Activate '// No need to activate a sheet if you've set a reference to it.
Do While c < 97
Cells(4, a).Select '// No need to select a range, you can access it's properties and methods directly.
'// The below formula will work if 'rr' is on the ActiveSheet, however the "rr" range has been set, and so it's address will never change unless you change the range that "rr" is actually set to
Cells(4, a).Formula = "=VLOOKUP($A$4;" & rr.Address & ";5;0)"
'// b, d & e are not used in the loop - so updating their values serves no purpose.
c = c + 1
a = a + 1
b = b + 1
d = d + 58
e = e + 58
Loop
End Sub
这是一个如何做到这一点的例子:
Dim counterInt As Integer, d As Integer, e As Integer
Dim ws1 As Excel.Worksheet, ws2 As Excel.Worksheet
d = 2
e = 59
Set ws1 = Sheets("Gefco")
Set ws2 = Sheets("Waberers")
For counterInt = 1 to 96
ws2.Cells(4, counterInt).Value = Application.Vlookup([A4], ws1.Range(ws1.Cells(d, 4), ws1.Cells(e, 4)), 5, False)
d = d + 58
e = e + 58
Next counterInt
Set ws1 = Nothing
Set ws2 = Nothing
答案 1 :(得分:0)
除了上述答案,您还可以在公式中使用R1C1表示法:
wws.Cells(4, a).FormulaR1C1 = "=VLOOKUP(R1C4, R" & d & "C4:R" & e & "C8,5,FALSE)"
答案 2 :(得分:0)
编辑解决方案以供参考。 由于SOofWXLS的上述解决方案,我能够用动态范围的VLOOKUPS填充从B4到CS61的所有表格,它逐行填充单元格:
Sub vlookup_rates_2()
Dim rowInt As Integer, counterInt As Integer, d As Integer, e As Integer
Dim ws1 As Excel.Worksheet, ws2 As Excel.Worksheet
d = 2
e = 59
Set ws1 = Sheets("Gefco")
Set ws2 = Sheets("Waberers")
For rowInt = 4 To 61
For counterInt = 1 To 96
ws2.Cells(rowInt, counterInt + 1).Value = Application.VLookup(Cells(rowInt, 1), ws1.Range(ws1.Cells(d, 4), ws1.Cells(e, 8)), 5, False)
d = d + 58
e = e + 58
Next counterInt
d = 2
e = 59
Next rowInt
Set ws1 = Nothing
Set ws2 = Nothing
End Sub