首页 文章

对于范围内的每个单元格,如果单元格值不为空,则vlookup

提问于
浏览
0

由于运行时错误“1004”,我很难让下面的代码运行:应用程序定义或对象定义的错误 .

通常当我遇到这个错误是由于纸张保护,我已经确保纸张不受保护,因此在子的开始处的线 .

我将在这里和最终目标支出这个方案:

Sheet1 = Live Contracts

此工作表包含一个包含6列和动态行数的表 . 第1列包含 Contract 参考编号 . 第2 - 6列与此无关 .

Sheet 4 = Contract Sums

此表包含所有 Contract ,相应的部门和 Contract 的 Value .

Goal

创建一个可以通过userform按钮调用的模块 .

模块需要查看sheet1的列A和每个单元格 - 如果有值 - 使用以下参数在G列中创建vlookup .

Lookup Value = Cell.offset(0, -6)

Table array = Sheet4.range("A3:C676")

Col_Index_Num = 1

FALSE - Exact match

该模块需要对该范围内的所有单元重复此过程 .

现在我已经制作了:

Worksheets("Live Contracts").Unprotect

Dim rng As range
Dim lastrow As Long
Dim cell As range
Dim contractrange As range

'Find dynamic range
lastrow = Worksheets("Live Contracts").range("A" & Rows.Count).End(xlUp).Row

Set contractrange = Worksheets("Contract Sums").range("A3:C676")
Set rng = Worksheets("Live Contracts").range("A2:A" & lastrow)

For Each cell In rng
'If cell does not equal blank then for each cell in column A, offset to column G.
    If cell.Value <> "" Then

    'In column G, vlookup column A cell value in contractrange's column C, only return exact match
        cell.Offset(0, 6).Value = Application.VLookup(cell.Offset(0, -6), contractrange, 1, False)

        'In column H, vlookup column A cell value in contractrange's column A, only return exact match
        cell.Offset(0, 7).Value = Application.VLookup(cell.Offset(0, -7), contractrange, 3, False)
    End If
    'Repeat for all cells in range
Next cell


End Sub

调试时突出显示以cell.offset开头的第一行

P.S我对VBA比较新,对代码不好道歉!

1 回答

  • 1

    看起来您可能混淆了活动单元格的使用以及循环中使用的 Cell . Cell 仅在完整循环迭代后才会更改 . 它不像是在选择不同的单元格后会发生变化的活动单元格 .

    因此,当您使用 Cell.offset(0,6) 时, Cell 没有更改,因此您无需尝试在Vlookup中使用 Cell.offset(0,-6) .

    试试这个:

    For Each cell In rng
    'If cell does not equal blank then for each cell in column A, offset to column G.
        If cell.Value <> "" Then
    
        'In column G, vlookup column A cell value in contractrange's column C, only return exact match
            cell.Offset(0, 6).Value = Application.VLookup(cell, contractrange, 1, False)
    
            'In column H, vlookup column A cell value in contractrange's column A, only return exact match
            cell.Offset(0, 7).Value = Application.VLookup(cell, contractrange, 3, False)
        End If
        'Repeat for all cells in range
    Next cell
    
    
    End Sub
    

相关问题