vba - 使用查找功能时出错

标签 vba excel

我有两张床单。 Sheet1 :上周,sheet2 :本周。

我正在使用 sheet1 在 sheet2 的 A 列中查找我的 ID,如果它们匹配,我会将 sheet1 的 M 列中的值复制到 sheet2 的 M 列。

由于某种原因,我在 sheet1 中找不到的值被填充为“0”。我不希望这种情况发生,我的代码。我只想让代码查找 ID,如果它们匹配我想要的值,否则我不想打印任何东西。

有人可以建议我哪里出错了吗?

Sub lookup()
Dim tr As Long
Dim trsh As Long
tr = Sheets("ThisWeek").Cells(Rows.Count, "A").End(xlUp).Row
trsh = Sheets("ThisWeek").Cells(Rows.Count, "A").End(xlUp).Row
Sheets("ThisWeek").Range("M2:M" & tr).Formula = Application.WorksheetFunction.IfError(Application.VLookup(Sheets("ThisWeek").Range("A2:A" & trsh), Sheets("LastWeek").Range("$A:$P"), 13, 0), "")
End Sub

This is how my sheet1, resembles. I have the ID in column A and the Repsonsible in column M and the Updates in N and o respectively.
So, this is my sheet2, this week. Assuming the ID in column A and Result in column M. I have highlighted my result in red,( Even i dont find the ID, i get them printed as 0), I dont Need this.  I have in the next column, the result i am expecting

最佳答案

代替

Sheets("ThisWeek").Range("M2:M" & tr).Formula = Application.WorksheetFunction.IfError(Application.VLookup(Sheets("ThisWeek").Range("A2:A" & trsh), Sheets("LastWeek").Range("$A:$P"), 13, 0), "")

尝试
Dim cel as Range
For Each cel In Sheets("ThisWeek").Range("M2:M" & tr)
    cel.Offset(0, 1).Formula = Application.WorksheetFunction.IfError(Application.VLookup(cel, Sheets("LastWeek").Range("$A:$P"), 13, 0), "")
Next cel

虽然您的代码可以使用工作表和范围变量进行修改。并确保您使用正确的 trtrsh .

编辑:
Sub lookupPSQM()
    Dim thisWeekLR As Long, lastWeekLR As Long
    Dim thisWeekSht As Worksheet, lastWeekSht As Worksheet
    Dim rng As Range, cel As Range

    Set thisWeekSht = ThisWorkbook.Sheets("ThisWeek")
    Set lastWeekSht = ThisWorkbook.Sheets("LastWeek")

    thisWeekLR = thisWeekSht.Cells(Rows.Count, "A").End(xlUp).Row
    'lastWeekLR = lastWeekSht.Cells(Rows.Count, "A").End(xlUp).Row
    Set rng = thisWeekSht.Range("A2:A" & thisWeekLR)

    For Each cel In rng
        cel.Offset(0, 12).Formula = Application.WorksheetFunction.IfError(Application.VLookup(cel, Sheets("LastWeek").Range("$A:$P"), 13, 0), "")
    Next cel
End Sub

请参阅图片以供引用。

表上周

enter image description here

本周工作表

enter image description here

关于vba - 使用查找功能时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45209903/

相关文章:

Excel VBA 查找和替换

python - 如何使用Python将单元格的值包含在Excel文件名中?

java - Apache POI 事件用户模型将时间戳值读取为 double 值

vba - 动态调整表大小到最后一行?

excel - 查找最后一列和最后一行

excel - 我怎样才能加快循环

python - 不能用 pandas read_excel

vba - 我的代码生成一个无限循环

java - Apache POI 日期区域设置问题

vba - 如何在 Chrome 中使用 VBA + SELENIUM 计算类中的元素?