簡體   English   中英

Excel VBA-嵌套循環以格式化Excel表列

[英]Excel VBA - Nested loop to format excel table columns

到目前為止,我有一個宏,它將4個新表列添加到現有表(“ Table1”)中。 現在,我希望宏將第三行和第四行格式化為百分比。 我想將其包含在代碼中已列出的循環中。 我嘗試了幾種不同的方法來做到這一點。 我認為我不太了解UBound函數的工作原理,但是希望您能理解我正在嘗試做的事情。

我也不確定我是否可以繼續在嵌套For循環中使用關於“ lst”變量的WITH語句。

@Jeeped-我又在找你...感謝基本上讓我完成了整個項目

Sub attStatPivInsertTableColumns_2()

Dim lst As ListObject
Dim currentSht As Worksheet
Dim colNames As Variant, r1c1s As Variant 
Dim h As Integer, i As Integer

Set currentSht = ActiveWorkbook.Sheets("Sheet1")
Set lst = ActiveSheet.ListObjects("Table1")

colNames = Array("AHT", "Target AHT", "Transfers", "Target Transfers")
r1c1s = Array("=([@[Inbound Talk Time (Seconds)]]+[@[Inbound Hold Time (Seconds)]]+[@[Inbound Wrap Time (Seconds)]])/[@[Calls Handled]]", "=350", "=[@[Call Transfers and/or Conferences]]/[@[Calls Handled]]", "=0.15")

With lst
For h = LBound(colNames) To UBound(r1c1s)
    .ListColumns.Add
    .ListColumns(.ListColumns.Count).Name = colNames(h)
    .ListColumns(.ListColumns.Count).DataBodyRange.FormulaR1C1 = r1c1s(h)
  If UBound(colNames(h)) = 2 or UBound(colNames(h)) = 3 Then        
        For i = UBound(colNames(h), 2) To UBound(colNames(h), 3)
            .ListColumns(.ListColumns.Count).NumberFormat = "0%"
  End if
        Next i
Next h
End With

End Sub

您無需嵌套第二個for循環。 如果要將第3列和第4列設置為百分比,則只需要在循環( h )的迭代次數為2或3時進行設置(請記住該數組從0開始索引)。 您也不應在主循環中交叉數組,並且由於LBound在大多數情況下為0,因此您仍然可以使用它。 嘗試這個:

With lst
    For h = 0 To UBound(r1c1s)
        .ListColumns.Add
        .ListColumns(.ListColumns.Count).Name = colNames(h)
        .ListColumns(.ListColumns.Count).DataBodyRange.FormulaR1C1 = r1c1s(h)
        If h = 2 or h = 3 Then        
                .ListColumns(.ListColumns.Count).NumberFormat = "0%"
        End if
    Next h
End With

為了回答問題的另一點, UBound(array)只是給出給定數組中最大元素的索引(Upper BOUNDary)。 因此,在這樣的數組中有50個元素的地方, UBound(array)將返回49(如前所述,從零開始)。 LBound僅給出數組的另一端(Lower BOUNDary),通常為零。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM