Update sheet1 when a cell in sheet2 meets criteria - Excel and VBA

时间:2018-12-03 13:20:59

标签: excel vba if-statement

With VBA, I'm trying to get an update in a cell-value when it meets the criteria given to another sheets cell. So far it gives me an "Error 5 - Invalid procedure call or argument".

Without this "IF - Then" it worked fine. Now I'd like to refine my procedure, by only updating cell1 from table "t_Magazijnvoorraad" when in table "t-Bestellijst" the cell in column "VERZONDEN" has a value "J".

Dim rng1, rng2, cell1, cell2 As Range
Dim lastRow1 As Long
lastRow1 = Range("t_Magazijnvoorraad[PRODUCTCODE]").End(xlUp).Row
Set rng1 = Range("t_Magazijnvoorraad[PRODUCTCODE]")

Dim lastRow2 As Long
lastRow2 = Range("t_Bestellijst[PRODUCTCODEKOPIE]").End(xlUp).Row
Set rng2 = Range("t_Bestellijst[PRODUCTCODEKOPIE]")

If Cells("t_Bestellijst[VERZONDEN]") = "j" Then
  For Each cell1 In rng1
  If IsEmpty(cell1.Value) Then Exit For

  For Each cell2 In rng2
  If IsEmpty(cell2.Value) Then Exit For

  If cell1 = cell2 Then
    cell1.Offset(0, 5) = cell1.Offset(0, 5) - cell2.Offset(0, 1)
    End If
  Next cell2
  Next cell1
Else: End If

The error occurs at:

If Cells("t_Bestellijst[VERZONDEN]") = "j" Then

1 个答案:

答案 0 :(得分:1)

单元格有两个参数;代表行和列序号的数字。

范围可以采用表示xlA1样式单元格/范围引用或列表对象结构化表引用的字符串,如您正在使用的那样。

不幸的是,仅更改为Range("t_Bestellijst[VERZONDEN]")并不能解决您的问题,因为这似乎是表的完整列,并且您无法将值的完整列与单个字母进行比较,并且期望任何可靠的方法,逻辑布尔比较。您不能将一列值与单个值进行比较;您可能需要遍历它们,并将列中的每个单元格与单个值进行比较。

'this isn't going to work
If Range("t_Bestellijst[VERZONDEN]") = "j" Then
    'do something
end if

'but this might
dim r as range
for each r in Range("t_Bestellijst[VERZONDEN]")
    If r = "j" Then
        'do something here
    end if
next r