2014-10-10 76 views
-5

任何人都可以帮助我寻找一种将代码优化为更短行的好方法吗?请给我一个好的建议。VBA Excel forLoop优化

With Selection 
       .Value = "Apple" 
       .Font.Bold = True 
       .Offset(1).Value = "Orange" 
       .Offset(1).Font.Bold = True 
       .Offset(2).Value = "Strawberry" 
       .Offset(2).Font.Bold = True 
       .Offset(3).Value = "Pear" 
       .Offset(3).Font.Bold = True 
       .Offset(4).Value = "Pineapple" 
       .Offset(4).Font.Bold = True 
       .Offset(5).Value = "Grape" 
       .Offset(5).Font.Bold = True 
       .Offset(6).Value = "Banana" 
       .Offset(6).Font.Bold = True 
       .Offset(8).Value = "Durian" 
       .Offset(8).Font.Bold = True 
       .Offset(8, 1).Value = "Rambutan" 
       .Offset(8, 1).Font.Bold = True 
       .Offset(8, 2).Value = "Dragonfruit" 
       .Offset(8, 2).Font.Bold = True 
       .Offset(8, 3).Value = "Mango" 
       .Offset(8, 3).Font.Bold = True 
      End With 
+5

如果您没有任何错误或具体的“如何”问题,那么优化问题更适合StackOverflow的[代码评论](http://codereview.stackexchange.com/)姊妹网站。 – 2014-10-10 02:39:07

回答

3

为您的水果创建一个源数组。

Dim fruits 
fruits = Array("Apple", "Orange", ... , "Mango") 

然后使用循环将值分配给范围。
您需要额外的变量。

Dim n As Long, fruit 

With Selection: n = 0 
    For Each fruit In fruits 
     .Offset(n) = fruit: n = n + 1 
    Next 
    .Resize(n + 1).Font.Bold = True '~~> format in one go 
End With 

我不知道你是否会考虑这个优化足够,但HTH。
顺便说一句,当你分配水果Rambutan我没有考虑列中的转变。
我把它留给你。它可能需要另一个变量和IF语句

+0

一个循环,不易辨认和勉强缩短 - 是否真的被推荐? – pnuts 2014-10-10 02:51:01

+2

OP的样本数据可能存在拼写错误,但第八行(例如'.OFFSET(7)')也被跳过。 – Jeeped 2014-10-10 03:09:54

+1

@pnuts我提到的是OP的短线要求。 :)另外,我把它留给他。 – L42 2014-10-10 05:00:35