2014-10-10 100 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