excel - VBA 将粘贴的行设置为范围
问题描述
下面是从工作表“模板”复制范围并粘贴到活动工作表上的第一个空白行的代码的一部分。第 1 行是标题行。
我想要做的是参考刚刚粘贴的行,以便然后Group
行。
我的 VBA 很差,我不确定如何正确设置“PastedRange”。我怎么能做到这一点?
Dim copySheet As Worksheet
Dim pasteSheet As Worksheet
Dim LRow As Long
Dim PastedRange As Range
Set copySheet = ThisWorkbook.Worksheets("Template")
Set pasteSheet = ThisWorkbook.ActiveSheet
Set PastedRange = .Range("A" & .Rows.Count).End(xlUp).Row
With pasteSheet
'~~> Find the last cell to write to
If Application.WorksheetFunction.CountA(.Cells) = 0 Then
LRow = 2
Else
LRow = .Range("A" & .Rows.Count).End(xlUp).Row + 1
End If
copySheet.Range("2:" & copySheet.Cells(Rows.Count, _
1).End(xlUp).Row).Copy
.Rows(LRow).PasteSpecial Paste:=xlPasteAll
PastedRange.Group
End With
解决方案
请尝试下一个代码。它将对所有粘贴的行进行分组,除了第一行:
Sub testGroupRows()
Dim copySheet As Worksheet, pasteSheet As Worksheet, LRow As Long, csLastRow As Long
Set copySheet = ThisWorkbook.Worksheets("Template")
Set pasteSheet = ThisWorkbook.ActiveSheet
With pasteSheet
'~~> Find the last cell to write to
If Application.WorksheetFunction.CountA(.cells) = 0 Then
LRow = 2
Else
LRow = .Range("A" & .rows.count).End(xlUp).row + 1
End If
'if the summary row is not above, set it to be above:
If .Outline.SummaryRow <> xlSummaryAbove Then .Outline.SummaryRow = xlSummaryAbove
csLastRow = copySheet.cells(rows.count, 1).End(xlUp).row
copySheet.Range("2:" & csLastRow).Copy
.rows(LRow).PasteSpecial Paste:=xlPasteAll
'group skipping the first copied row:
.Range(.cells(.rows.count, 1).End(xlUp), .cells(.rows.count, 1).End _
(xlUp).Offset(-(csLastRow - 3), 1)).EntireRow.Group
End With
End Sub
推荐阅读
- r - 替代 data.table 中的 plyr::mapvalues
- ffmpeg - 是否可以使用 ffprobe 确定字幕轨道是基于图像还是基于文本
- javascript - 滚动时在两个像素值之间显示 div
- matlab - 迭代变量时的 Newton Raphson 方法问题
- android - 杀死应用程序后启动的服务被杀死
- javascript - myElement.textContent 显示不一致
- javascript - 带有 GatsbyJS 的 JSON-LD 架构用于丰富的片段
- if-statement - 等效于 Halide 的 If 语句
- java - JSR 303 - 如何通过注释以编程方式获取验证器实例?
- python - Match.expand 用法示例