VBA增加了VLOOKUP的dynamic范围

我在设置适当的VLOOKUPdynamic范围方面遇到了麻烦,每个循环应增加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 

我认为范围是有些错误的定义,但我不能破解它。 请halp。

谢谢!

以下是你做错的一些事情:

 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 

除了上面的答案之外,还可以在公式中使用R1C1表示法:

 wws.Cells(4, a).FormulaR1C1 = "=VLOOKUP(R1C4, R" & d & "C4:R" & e & "C8,5,FALSE)" 

编辑解决scheme以供参考。 得益于上面的SOOWXLS的解决scheme,我可以用VLOOKUPS的dynamic范围填充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