首页 > 解决方案 > 当 sheet2 中的单元格符合条件时更新 sheet1 - Excel 和 VBA

问题描述

使用 VBA,当单元格值满足为另一个工作表单元格提供的标准时,我试图在单元格值中获取更新。到目前为止,它给了我一个“错误 5 - 无效的过程调用或参数”。

如果没有这个“IF - Then”,它工作得很好。现在我想改进我的程序,只更新表“t_Magazijnvoorraad”中的cell1,而表“t-Bestellijst”中的“VERZONDEN”列中的单元格的值为“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

错误发生在:

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

标签: excelvbaif-statement

解决方案


Cells 有两个参数;表示行和列序数的数字。

Range 可以采用表示 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

推荐阅读