我在宏中创建了很多表。所以我试图创建一个模块table_mod,它生成表并将它放在现有最后一行下面的三行,并且我计划在需要创建表时调用table_mod。但我遇到的事实是我需要我的变量依赖于用户提供的表名。例如:
Sub Main()
' Below are all the data that my macro will generate in its number crunching
var_12_count = "Jordan"
var_13_count = "Kobe"
var_21_count ="Rings"
var_22_count = 6
var_23_count = 5
var_title_count = "This table lists the number of rings won by Jordan and Kobe"
var_12_transpose = "Rings"
var_21_transpose = "Jordan"
var_31_transpose = "Kobe"
var_22_transpose = 6
var_32_transpose = 5
var_title_transpose = "This is the transpose of the previous table"
' My intention is to call table commands like this to spit out the earlier generated data in nicely formatted tables.
table_mod(2,3,"count")
table_mod(3,2,"transpose")
End Sub
Sub table_mod(row As Long, column As Long, name As String)
Set wb As ActiveWorkbook
Set ws As wb.ActiveSheet
With ws
lr = .Range("A" & .Rows.Count).End(xlUp).Row
.Cells(lr+3,1).Value = var_title_&name
For i = 1 To row
For j = 1 To column
.Cells(lr+6+i,j).Value = var_&CStr(i)&CStr(j)&_&name
Next j
Next i
End With
End Sub
输出应该看起来像
This table lists the number of rings won by Jordan and Kobe
Jordan Kobe
Rings 6 5
This is the transpose of the previous table
Rings
Jordan 6
Kobe 5
但我不知道如何将变量值与字符串组合在一起,以便VBA知道从正确的变量中读取值。
我对以某种替代方式创建格式化/标准化表格的任何建议持开放态度。我打算让我的所有表格在行,字体,颜色等方面具有相同的格式,但我没有包括代码的所有这些方面。现在我的线条上出现了红色的彩色线条和意外的结束信息。感谢
如果我让这个工作,我希望与每个重复的过程,实际上宏的每个过程。我猜的是每个人都是如何做事的。
答案 0 :(得分:1)
对于Siddharth Rout的建议,我做了这个并且它有效!!!!
Dim tabArray As Variant
'I defined the array of tables values outside everything because otherwise the other Sub was not able to access it.
Sub Main()
ReDim tabArray(0 To 10, 0 To 10, 0 To 0)
' Apparently, you can only ReDim the last dimension, so I picked some large number for the first two dimensions, which are my rows and columns and then the last dimension will be my table title. I will keep incrementing it as I add more tables.
tabArray(0, 0, 0) = "This table lists the number of rings won by Jordan and Kobe"
tabArray(1, 2, 0) = "Jordan"
tabArray(1, 3, 0) = "Kobe"
tabArray(2, 1, 0) = "Rings"
tabArray(2, 2, 0) = 6
tabArray(2, 3, 0) = 5
ReDim Preserve tabArray(0 To 10, 0 To 10, 0 To 1)
tabArray(0, 0, 1) = "This is the transpose of the previous table"
tabArray(2, 1, 1) = "Jordan"
tabArray(3, 1, 1) = "Kobe"
tabArray(1, 2, 1) = "Rings"
tabArray(2, 2, 1) = 6
tabArray(3, 2, 1) = 5
Call table_mod(2, 3, 0)
Call table_mod(3, 2, 1)
End Sub
Sub table_mod(row As Long, column As Long, number As Integer)
lr = Range("A" & Rows.Count).End(xlUp).row
Cells(lr + 3, 1).Value = tabArray(0, 0, number)
For i = 1 To row
For j = 1 To column
Cells(lr + 6 + i, j).Value = tabArray(i, j, number)
Next j
Next i
End Sub
这完美无缺,但从巨大阵列开始,似乎是浪费空间。如果有一些方法可以使行和变量保持灵活,就像可能有一个“数组数组”,其中一个数组是表数据的2D数组,主数组包含它并包含表名。这可能吗?
再次感谢Siddharth Rout建议Arrays。