Excel精英培训网

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

[已解决]求同行循环简写代码

[复制链接]
发表于 2016-2-14 19:37 | 显示全部楼层 |阅读模式
1.png
如上图示,运行以下代码:
Sub Macro1()
Dim arr, d, d2, i%, j%
Set d = CreateObject("scripting.dictionary")
Set d2 = CreateObject("scripting.dictionary")
arr = [a1:i1]
For j = 1 To UBound(arr, 2)
    x = arr(1, j)
    For i = 1 To Len(x)
        s = Mid(x, i, 1)
        d(s) = d(s) + 1
    Next
Next
For Each a In d.keys
    If d(a) = 2 Then d2(a) = ""
Next
For j = 1 To UBound(arr, 2)
    x = arr(1, j)
    p = ""
    For i = 1 To Len(x)
        s = Mid(x, i, 1)
        If d2.exists(s) Then p = p & s
    Next
    If Len(p) = 2 Then Cells(1, j) = p: Cells(1, j).Font.Size = 36
Next
End Sub
得到如下效果:
3.png
代码只对第一行有效,如果我想对9行都有效,应如何改善代码?
发觉代码只要更改黄色背景字的区域即可,但写类似同样的9个代码实在太麻烦了。
能否在此代码基础上改善?哪位大神可以啊?可以得出如下效果:
2.png



最佳答案
2016-2-14 20:05
  1. Sub Macro1()
  2. Dim arr, d, d2, i%, j%, k%
  3. Set d = CreateObject("scripting.dictionary")
  4. Set d2 = CreateObject("scripting.dictionary")
  5. For k = 1 To 9
  6.     arr = Cells(k, 1).Resize(1, 9)
  7.     For j = 1 To UBound(arr, 2)
  8.         x = arr(1, j)
  9.         For i = 1 To Len(x)
  10.             s = Mid(x, i, 1)
  11.             d(s) = d(s) + 1
  12.         Next
  13.     Next
  14.     For Each a In d.keys
  15.         If d(a) = 2 Then d2(a) = ""
  16.     Next
  17.     For j = 1 To UBound(arr, 2)
  18.         x = arr(1, j)
  19.         p = ""
  20.         For i = 1 To Len(x)
  21.             s = Mid(x, i, 1)
  22.             If d2.exists(s) Then p = p & s
  23.         Next
  24.         If Len(p) = 2 Then Cells(k, j) = p: Cells(k, j).Font.Size = 36
  25.     Next
  26.     d.RemoveAll: d2.RemoveAll
  27. Next
  28. End Sub
复制代码

每行循环处理.zip

13.73 KB, 下载次数: 4

excel精英培训的微信平台,每天都会发送excel学习教程和资料。扫一扫明天就可以收到新教程
发表于 2016-2-14 20:05 | 显示全部楼层    本楼为最佳答案   
  1. Sub Macro1()
  2. Dim arr, d, d2, i%, j%, k%
  3. Set d = CreateObject("scripting.dictionary")
  4. Set d2 = CreateObject("scripting.dictionary")
  5. For k = 1 To 9
  6.     arr = Cells(k, 1).Resize(1, 9)
  7.     For j = 1 To UBound(arr, 2)
  8.         x = arr(1, j)
  9.         For i = 1 To Len(x)
  10.             s = Mid(x, i, 1)
  11.             d(s) = d(s) + 1
  12.         Next
  13.     Next
  14.     For Each a In d.keys
  15.         If d(a) = 2 Then d2(a) = ""
  16.     Next
  17.     For j = 1 To UBound(arr, 2)
  18.         x = arr(1, j)
  19.         p = ""
  20.         For i = 1 To Len(x)
  21.             s = Mid(x, i, 1)
  22.             If d2.exists(s) Then p = p & s
  23.         Next
  24.         If Len(p) = 2 Then Cells(k, j) = p: Cells(k, j).Font.Size = 36
  25.     Next
  26.     d.RemoveAll: d2.RemoveAll
  27. Next
  28. End Sub
复制代码
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-20 21:17 , Processed in 0.245447 second(s), 9 queries , Gzip On, Yac On.

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

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