我有没有办法列出清单。我正在尝试制作一个评论日志,其中包括姓名---日期---评论。我将有3本工作簿。两个工作簿将有两个不同的名称,日期和注释列表,然后我希望第三个工作簿根据日期将这些列表收集到一个主列表中。我将如何为此编程宏? 我理解VBA录音机。我的问题是列表的大小未确定。例如,一本书中可能有5条评论,第二本书中可能有3条评论。我希望主列表根据输入的日期按顺序排列8条评论日志。
答案 0 :(得分:1)
嘿,我感到无聊无论如何。我在发布您的最新评论之前写了这个,但是如果您有动态范围,那么无论我在哪里使用CurrentRegion属性作为源,您都可以替换这些范围的名称。看看你能不能这样做;它至少应该指向正确的方向。
Sub CombineLists2()
Dim rng_Source As Excel.Range
Dim rng_Target As Excel.Range
Dim wbk_1 As Excel.Workbook
Dim wbk_2 As Excel.Workbook
Dim wbk_3 As Excel.Workbook
On Error GoTo ErrorHandler
'I'd recommend doing a test here to ensure that
'all three workbooks are open, which is one reason
'that we're using object variables.
'If one of the workbooks isn't open then it'll throw an error.
'Obviously change the names to your own files.
Set wbk_1 = Application.Workbooks("ATeam.xlsx")
Set wbk_2 = Application.Workbooks("BTeam.xlsx")
Set wbk_3 = Application.Workbooks("CTeam.xlsm")
'You may want to delete any contents that are in the combined book first.
wbk_3.Worksheets(1).Range("A1").CurrentRegion.Clear
'We'll now get a reference to the range containing the list.
'You'll obviously have to change the references to suit where
'your list is.
'In this case we'll take the headings as well.
'Note that CurrentRegion range will only work if there
'is nothing directly adjacent to the list.
wbk_1.Worksheets(1).Range("A1").CurrentRegion.Copy _
Destination:=wbk_3.Worksheets(1).Range("A1")
'That's the first workbook done.
'The second one we may need to tweak a little because we
'don't want the headings this time.
'I'm going to use a range reference for this so that
'it'll be a little more transparent than doing it in one go.
'First we grab the whole list range including headings, just
'as we did for the first list.
Set rng_Source = wbk_2.Worksheets(1).Range("A1").CurrentRegion
'Next, we offset that by 1 row and shrink the size of it by
'1 row to get rid of the headings.
Set rng_Source = rng_Source.Offset(1, 0) _
.Resize(rng_Source.Rows.Count - 1, rng_Source.Columns.Count)
'I'll use another range to get the location of the existing list
'in the combined workbook.
Set rng_Target = wbk_3.Worksheets(1).Range("A1").CurrentRegion
'Now we copy the second list and paste it to one cell below that range
rng_Source.Copy Destination:=rng_Target.Offset(rng_Target.Rows.Count, 0)
ExitPoint:
On Error Resume Next
Set wbk_3 = Nothing
Set wbk_2 = Nothing
Set wbk_1 = Nothing
Set rng_Source = Nothing
Set rng_Target = Nothing
On Error GoTo 0
Exit Sub
ErrorHandler:
MsgBox "Error " & Err.Number & vbCrLf & Err.Description
Resume ExitPoint
End Sub
答案 1 :(得分:0)
在鼓励尝试问题的StackOverflow精神中,我提出以下建议。
您熟悉宏录制器吗? (它位于“开发人员”选项卡上(您可能需要在Excel功能区选项中公开)。)
如果您记录手动执行此操作的操作,宏录制器将生成您需要的90%的代码。
其余的将涉及您只需用动态引用(如CurrentRegion)替换硬编码范围引用,以获取列表的内容。如果您不愿意这样做,请务必再次发布。
我建议您在第三个(目标)工作簿中记录宏,以便它可以简单地从源工作簿中获取内容。