我还是VBA的新手,我正在尝试在第4行的下一个可用列中执行vlookup,直到vlookup的使用范围结束。另外,一旦vlookup完成,在我需要对上面单元格中的所有值求和的行中。如果这令人困惑,这是我到目前为止的代码:
{{1}}
我在哪里“* 4:*”是我想象的,我需要将数据放入下一个可用列。在那之后,我只需要在该列的下一个可用列中对该列中的所有内容求和。有人可以帮忙吗?
答案 0 :(得分:1)
查找下一个可用列并在范围中插入公式并在底部汇总。如果列数大于26,则需要对其进行修改。
Dim SourceLastRow As Long
Dim OutputLastRow As Long
Dim sourceSheet As Worksheet
Dim outputSheet As Worksheet
Dim NextColumn As Long
Dim ColumnStr As String
Dim ColumnStr2 As String
Dim ColumnStr3 As String
Set sourceSheet = Worksheets("Data1")
Set outputSheet = Worksheets("Pivot")
With sourceSheet
SourceLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
With outputSheet
NextColumn = .Cells(4, Columns.Count).End(xlToLeft).Column + 1
If NextColumn + 1 < 27 Then
ColumnStr = Chr(64 + NextColumn + 1)
Else
ColumnStr = Chr(64 + Int((NextColumn + 1) / 26)) & Chr(64 + ((NextColumn + 1) Mod 26))
End If
If NextColumn - 1 < 27 Then
ColumnStr3 = Chr(64 + NextColumn - 1)
Else
ColumnStr3 = Chr(64 + Int((NextColumn - 1) / 26)) & Chr(64 + ((NextColumn - 1) Mod 26))
End If
If NextColumn < 27 Then
ColumnStr2 = Chr(64 + NextColumn)
Else
ColumnStr2 = Chr(64 + Int((NextColumn) / 26)) & Chr(64 + ((NextColumn) Mod 26))
End If
OutputLastRow = .Cells(.Rows.Count, "D").End(xlUp).Row
.Range(Cells(4, NextColumn), Cells(OutputLastRow, NextColumn)).Formula = _
"=VLOOKUP(D4,'" & sourceSheet.Name & "'!$A$2:$H$" & SourceLastRow & ",3,0)" & "*" & ColumnStr3 & 4
DoEvents
.Cells(OutputLastRow + 1, NextColumn).Formula = "=SUM(" & ColumnStr2 & "4:" & ColumnStr2 & OutputLastRow & ")"
End With