我从导入到 Excel 的程序中获得以下格式的输出:
Item 1
1 10
2 10
3 20
5 20
8 30
13 30
Item 2
1 40
2 40
3 50
5 50
8 60
13 60
Item 3
1 50
2 50
3 40
5 40
8 30
13 30
现在,我想创建一个表,其中每个项目的值彼此相邻放置,如下所示:
Item 1 Item 2 Item 3
1 10 40 50
2 10 40 50
3 20 50 40
5 20 50 40
8 30 60 30
13 30 60 30
我可以想办法使用公式和
INDIRECT
的组合来做到这一点其他功能,但我可以立即看到这将是一个巨大的痛苦。有没有聪明的方法来做到这一点?我的方法是这样的:
=VLOOKUP($A6;indirect("A"&(6+G$5*$X$4):"D"&(30+G$5*$X$4));4;FALSE)
我的第一个查找表来自
A6:D30
,第二个来自 A32:D56
. X4
包含值 26
这是每个项目的行数,G5:AA5
是 0, 1, 2 ...
.我会把它放在
Item 1
之外列出并将其横向和向下拖动。我认为该程序应该可以工作,但出现语法错误。我没有太多编写 VBA 的经验,但我能够阅读和理解它。
更新:
应悉达多的要求:
最佳答案
你能看看这个。
它采用固定格式,如您的示例中所示。
它可以是动态的,但是您需要自定义代码。
Option Explicit
Sub test()
Dim oCollection As Collection
Dim oDict As Variant
Dim oItem As Object
Dim iCnt As Integer
Dim iCnt_B As Integer
Dim iCnt_items As Integer
Dim iCnt_records As Integer
Dim iID As Integer
Dim iValue As Integer
Dim strKey As Variant
'Nr of items
iCnt_items = 3
'Records per item
iCnt_records = 6
'This dictionary will store the items
Set oCollection = New Collection
'Store dictionaries in collection
For iCnt = 0 To iCnt_items - 1
Set oDict = CreateObject("Scripting.Dictionary")
For iCnt_B = 1 To iCnt_records
iID = ThisWorkbook.Sheets(1).Cells((iCnt * (iCnt_records) + (iCnt + 1) + iCnt_B), 1).Value
Debug.Print iID
iValue = ThisWorkbook.Sheets(1).Cells((iCnt * (iCnt_records) + (iCnt + 1) + iCnt_B), 2).Value
Debug.Print iValue
oDict.Add iID, iValue
Next iCnt_B
oCollection.Add oDict, "item " & iCnt
Next iCnt
'Write collection to sheet
iCnt = 0
For Each oItem In oCollection
iCnt = iCnt + 1
ThisWorkbook.Sheets(2).Cells(1, 1 + iCnt).Value = "item " & iCnt
iCnt_B = 0
For Each strKey In oItem.keys
iCnt_B = iCnt_B + 1
ThisWorkbook.Sheets(2).Cells(1 + iCnt_B, 1).Value = strKey
ThisWorkbook.Sheets(2).Cells(1 + iCnt_B, 1 + iCnt).Value = oItem(strKey)
Next
Next oItem
End Sub
编辑:抱歉打断了对话->我在编程时没有跟进评论部分。
边注:
如果您使用的范围是动态的,我会使用字典。
我之所以这么说是因为字典对象在其记录上使用了索引。
键对结构为:ID、值
允许您直接访问与给定 ID 对应的值。
在您的示例中,您正在使用清晰的 ID - 值结构。
使用数字 id 实际上是最快的。
关于excel - 从 Excel 中导入的列表制作表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19493543/