Vlookup跨多张床单

时间:2017-05-25 02:36:34

标签: excel vba excel-vba vlookup

这背后的想法是在第11列到第1页的G列:AI上使用vba vlookup 。标题在所有工作表的第3行结束。

我写了如下代码。代码停在ws1.Cells(r, c).Value = Application.WorksheetFunction.VLookup(ws1.Cells(r, 1).Value, ws2.Range("A1:AI500"), colnum, False)显示的子集超出范围,有时甚至

  

运行时错误'1004':无法获取WorksheetFunction类的VLookup属性。

请就前进的方向提出建议。

我想发送文件以便更好地澄清,但似乎无法找到附加功能。谢谢 !

Sub green_update()


Dim wb As Workbook, ws1 As Worksheet, ws2 As Worksheet

Set wb = ThisWorkbook
Set ws1 = wb.Sheets("Sheet1")
Set ws2 = wb.Sheets("Sheet13")

Dim bil As String
Dim lastrow As Long
Dim for_col As Long, i As Long, r As Long, c As Long, colnum As Long
r = 4: c = 7: colnum = 7

'mysheets = "sheet11:sheet12:sheet13"
'i would like to allow vlookup to search through all sheet 11-13

For for_col = 1 To ws2.Cells("4", Columns.Count).End(xlToLeft).column
lastrow = ws2.Cells(Rows.Count, "A").End(xlUp).row

    For i = 1 To lastrow - 3

    ws1.Cells(r, c).Value = Application.WorksheetFunction.VLookup(ws1.Cells(r, 1).Value, ws2.Range("A1:AI500"), colnum, False)
    r = r + 1
    Next

 r = 4
 colnum = colnum + 1
 c = c + 1

Next

End Sub

2 个答案:

答案 0 :(得分:1)

我在代码中解释了我的答案,但总结了你的问题:

1 - 您没有定义变量,尤其是工作表。永远不要假设您的工作表,并始终定义和设置对工作簿和工作表的引用

2 - 您正在使用A列的行号和第3行的列号来限制For loops,但如果它们为空或与您的查询轮次不兼容会怎样?然后您可能会收到错误或错误的结果。仔细定义它们。

Option Explicit

Sub green_update()
Dim wb As Workbook, ws1 As Worksheet, ws2 As Worksheet

Set wb = ThisWorkbook
Set ws1 = wb.Sheets("Sheet1") 'Change this Sheet1 name with your current Worksheet name
Set ws2 = wb.Sheets("mysheets")

Dim bil As String 'I don't know where do you use that variable.
Dim lastrow As Long 'Prefer to work with Long instead of Integer
Dim for_col As Long, i As Long, r As Long, c As Long, colnum As Long
r = 4: c = 7: colnum = 7


     For for_col = 1 To ws2.Cells("4", Columns.Count).End(xlToLeft).Column
'This is important! Here in this case are you sure you, _ 
'you would like to define how many times your For loop will run based on 3rd row?     

lastrow = ws2.Cells(Rows.Count, "A").End(xlUp).Row

'This is also important! Are you sure you would like to run your For loop_
'based on the row number of A column? I think you should define it -3 _
'because you start your lookup from D4 (so first 3 one Is not necessary)

        For i = 1 To lastrow - 3
            ws1.Cells(r, c).Value = WorksheetFunction.VLookup(ws1.Cells(r, 4).Value, ws2.Range("A1:AI500"), colnum, False)
            r = r + 1
        Next
 r = 4
 colnum = colnum + 1
 c = c + 1

     Next
End Sub

答案 1 :(得分:1)

因为你已经完全改变了你的要求..我正在发布另一个答案,以明确。 您的请求仍然不完全清楚,因此某些输入可能指向错误的目的地,但您可以轻松更改这些输入。 如果您不理解任何部分,请随时再次询问。

'