简体   繁体   中英

Excel VBA - Nested loop to format excel table columns

I have a macro that so far, adds 4 new table columns to an existing table ("Table1"). Now, I would like the macro to format the 3rd and 4th row as percentage. I would like to include this in the loop already listed in my code. I have tried several different ways to do this. I don't think I quite understand how the UBound function works, but hopefully you can understand what I am trying to do.

I also am unsure if I am allowed to continue to utilize the WITH statement in my nested For loop in regards to me 'lst' variable.

@Jeeped - I'm looking at you for this one again...thanks for basically walking me through this whole project lol

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

You don't need to nest a second for loop. If you want to set the 3rd and 4th columns to a percentage, you only need to set that when the iteration of the loop ( h ) is 2 or 3 (remembering that arrays index from 0). You also shouldn't cross arrays for the main loop, and since LBound is in most cases 0 you might as well just use that anyway. Try this:

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

To answer the other point in your question, UBound(array) just gives the index of the largest element (the Upper BOUNDary) in the given array. So where you have 50 elements in such an array, UBound(array) will return 49 (zero based as mentioned before). LBound just gives the other end of the array (the Lower BOUNDary), which is generally zero.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM