Excel VBA – 嵌套循环来格式化Excel表格列

到目前为止,我有一个macros,将4个新的表列添加到一个现有的表(“Table1”)。 现在,我想macros以格式的第三和第四行作为百分比。 我想包括在我的代码中已经列出的循环。 我已经尝试了几种不同的方法来做到这一点。 我不认为我很理解UBound函数是如何工作的,但希望你能理解我正在做的事情。

我也不确定是否允许继续在嵌套的For循环中使用WITH语句来处理我的'lst'variables。

@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)只给出给定数组中最大元素(上边界)的索引。 因此,在这样一个数组中有50个元素的情况下, UBound(array)将返回49(如前所述,返回0)。 LBound只是给出数组的另一端(下边界),一般为零。