我有一个宏,到目前为止,将4个新表列添加到现有表(“Table1”)。现在,我希望宏将第3行和第4行格式化为百分比。我想在我的代码中列出的循环中包含它。我尝试了几种不同的方法来做到这一点。我不认为我完全理解UBound功能是如何工作的,但希望你能理解我想要做的事情。
我也不确定是否允许我继续在我的嵌套For循环中使用WITH语句来关于我'lst'变量。
@Jeeped - 我再次看着你这个...感谢基本上让我完成整个项目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
答案 0 :(得分:1)
您不需要嵌套第二个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),通常为零。