写一个VBA代码:表格A列值进行唯一值列显示,“B列值进行唯一值列做标题显示、C列值“对应A列值、B列值进行批量转置
时间: 2024-01-24 12:04:13 浏览: 115
行转列VBA宏工具,纯粹VBA代码编写
以下是该VBA代码:
```
Sub TransposeData()
Dim lastRow As Long
Dim uniqueValuesA As Variant
Dim uniqueValuesB As Variant
Dim uniqueCountA As Long
Dim uniqueCountB As Long
Dim i As Long, j As Long, k As Long
Dim dictA As Object
Dim dictB As Object
Dim arrTransposeA As Variant
Dim arrTransposeB As Variant
Dim arrData As Variant
'Get the last row of data in sheet A
lastRow = Sheets("A").Cells(Rows.Count, 1).End(xlUp).Row
'Get unique values in column A
uniqueValuesA = Sheets("A").Range("A2:A" & lastRow).Value
uniqueValuesA = WorksheetFunction.Transpose(WorksheetFunction.Unique(uniqueValuesA))
uniqueCountA = UBound(uniqueValuesA)
'Get unique values in column B
uniqueValuesB = Sheets("A").Range("B2:B" & lastRow).Value
uniqueValuesB = WorksheetFunction.Transpose(WorksheetFunction.Unique(uniqueValuesB))
uniqueCountB = UBound(uniqueValuesB)
'Create dictionary objects for column A and column B
Set dictA = CreateObject("Scripting.Dictionary")
Set dictB = CreateObject("Scripting.Dictionary")
'Populate column A dictionary with unique values as keys
For i = 1 To uniqueCountA
dictA.Add uniqueValuesA(i), i
Next i
'Populate column B dictionary with unique values as keys
For i = 1 To uniqueCountB
dictB.Add uniqueValuesB(i), i
Next i
'Create transpose arrays for column A and column B
ReDim arrTransposeA(1 To uniqueCountA, 1 To uniqueCountB)
ReDim arrTransposeB(1 To uniqueCountA, 1 To uniqueCountB)
'Loop through data and populate transpose arrays
For i = 2 To lastRow
j = dictA(Sheets("A").Cells(i, 1).Value)
k = dictB(Sheets("A").Cells(i, 2).Value)
arrTransposeA(j, k) = Sheets("A").Cells(i, 1).Value
arrTransposeB(j, k) = Sheets("A").Cells(i, 3).Value
Next i
'Transpose arrays and paste into sheet B
Sheets("B").Range("A1").Resize(uniqueCountB, uniqueCountA).Value = WorksheetFunction.Transpose(arrTransposeA)
Sheets("B").Range("A2").Resize(uniqueCountB, uniqueCountA).Value = WorksheetFunction.Transpose(arrTransposeB)
End Sub
```
此代码将表格A中的列A值进行唯一值列显示,将列B值进行唯一值列做标题显示,将列C值“对应A列值、B列值进行批量转置,并将结果粘贴到表格B中。请确保已经在工作簿中创建了名为"A"和"B"的工作表。
阅读全文