Excel精英培训网

 找回密码
 注册
数据透视表40+个常用小技巧,让你一次学会!
查看: 3346|回复: 14

[已解决]用字典查询怎么没有值

[复制链接]
发表于 2017-8-25 12:12 | 显示全部楼层 |阅读模式
Sub t()
Dim i, s
i = Sheet1.Cells(Rows.Count, 1).End(3).Row
s = Sheet3.Cells(Rows.Count, 1).End(3).Row
Set d1 = CreateObject("Scripting.Dictionary")
For w = 2 To i
    d1(Sheet1.Cells(w, 3)) = Sheet1.Cells(w, 10)
Next w
For a = 2 To s
    If d1.exists(Sheet3.Cells(a, 3)) Then Sheet3.Cells(a, 4) = d1(Sheet1.Cells(w, 3))
Next a
Set di = Nothing
End Sub
Sheet1.Cells(w, 10)肯定是有值的,但是不知道为什么d1.exists结果出来都是空值
最佳答案
2017-8-25 16:18
我的理解是,根据sheet2的A列从sheet1中取值。
另,建议用数组。
  1. Sub t()
  2. Dim i, s
  3. i = Sheet1.Cells(Rows.Count, 1).End(3).Row
  4. s = Sheet2.Cells(Rows.Count, 1).End(3).Row
  5. Set d1 = CreateObject("Scripting.Dictionary")
  6. For w = 2 To i
  7.      d1(Sheet1.Cells(w, 1).Value) = Sheet1.Cells(w, 2)
  8. Next w
  9. For a = 2 To s
  10.      Sheet2.Cells(a, 2) = d1(Sheet2.Cells(a, 1).Value)
  11. Next a
  12. Set di = Nothing
  13. End Sub
复制代码
excel精英培训的微信平台,每天都会发送excel学习教程和资料。扫一扫明天就可以收到新教程
发表于 2017-8-25 12:22 | 显示全部楼层
Sheet1 看了怎么这么别扭
Sheet(1)
Sheets("Sheet1")
回复

使用道具 举报

发表于 2017-8-25 12:42 | 显示全部楼层
If d1.exists(Sheet3.Cells(a, 3)) Then Sheet3.Cells(a, 4) = d1(Sheet1.Cells(w, 3))这里错了,你看下这里的w值是多少
回复

使用道具 举报

发表于 2017-8-25 12:44 | 显示全部楼层
我估计应该改成
If d1.exists(Sheet3.Cells(a, 3)) Then Sheet3.Cells(a, 4) = d1(Sheet3.Cells(a, 3))
或者直接连if都不要了
Sheet3.Cells(a, 4) = d1(Sheet3.Cells(a, 3))
回复

使用道具 举报

发表于 2017-8-25 13:50 | 显示全部楼层
看看Sheet1.Cells(w, 10)的值,w=i
回复

使用道具 举报

 楼主| 发表于 2017-8-25 14:45 | 显示全部楼层
d1(Sheet1.Cells(w, 3)) = Sheet1.Cells(w, 10)
这一段好像都没起到作用, d1(Sheet1.Cells(w, 3))好像都是空值
回复

使用道具 举报

发表于 2017-8-25 15:33 | 显示全部楼层
d1(Sheet1.Cells(w, 3)) = Sheet1.Cells(w, 10)除了你确实想这么做,否则这是错的!错的!错的!
得写成:d1(Sheet1.Cells(w, 3).value) = Sheet1.Cells(w, 10),包括后的语句,要加.value
当然,如果你确实想的不是把其value作为字典的key,那就除外
回复

使用道具 举报

发表于 2017-8-25 15:42 | 显示全部楼层
上清宫主是对的。
但是,修改后估计还是会出现上面所说的问题,w变量只在w循环之中变化,w循环结束后,w就是个定值(=i+1),并且对应的行已经没有数据,也一样得不到想要的结果。
回复

使用道具 举报

 楼主| 发表于 2017-8-25 15:57 | 显示全部楼层
大灰狼1976 发表于 2017-8-25 15:42
上清宫主是对的。
但是,修改后估计还是会出现上面所说的问题,w变量只在w循环之中变化,w循环结束后,w就 ...

应该和.Value无关的,我也觉得是在a循环中,w是定值,所以在a循环中d1(Sheet1.Cells(w, 3)都是空值,请教一下您,应该怎么改好咧?
回复

使用道具 举报

发表于 2017-8-25 16:01 | 显示全部楼层
修改的话必须根据你的附件,根据你的要求才能判断。
我估计的原因在楼上已经说明了,也给出了解决方法,对不对无法判断。
但是,.value还是要加上去。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|Archiver|Excel精英培训 ( 豫ICP备11015029号 )

GMT+8, 2024-4-25 17:58 , Processed in 0.331185 second(s), 9 queries , Gzip On, Yac On.

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表