帮助VBA脚本

时间:2011-02-17 22:01:07

标签: excel excel-vba vba

首先,我是VBA的新手,但我想做的伪代码是:

 For All open Excel Files
 Copy all values in Colomns A,B, C and D
 Append into Tab 1 of output.xls

我很欣赏正确方向的一些指示。

由于

2 个答案:

答案 0 :(得分:2)

有时最好的学习方法是录制宏。

工具>宏 - 选择记录。

然后进入工作簿,选择A,B,C,D列,然后按CTRL + C,然后打开新的TaB和CTRL + V.

停止录制宏,然后ALT + F11查看生成的代码,这应该会给你10个启动器。

如果您需要帮助,了解生成的代码/它返回的内容,我们可以解释。

答案 1 :(得分:2)

录制宏的一些内容对您无法帮助,例如,使用For ... Each迭代工作簿中的每个工作表。下面是一些示例代码,指出您正确的方向。这将遍历所有打开的工作簿,并将前四列的内容复制到工作表中。

Sub joinAllSheets()
Dim ws As Worksheet
Dim wb As Workbook
Dim wsOutput As Worksheet
Dim lngRowCount As Long
Dim wbSource As Workbook

'create output workbook
Set wsOutput = Application.Workbooks.Add.Sheets(1)
lngRowCount = 1

'Iterate through each open workbook
For Each wb In Application.Workbooks

'if the current workbook is not our output workbook then
If wb.Name <> wsOutput.Name Then
    'iterate through each worksheet
    For Each ws In wb.Worksheets
    'copy the first four columns of the used range in the worksheet
    Application.Intersect(ws.UsedRange, ws.Range("A:D")).Copy _
            Destination:=wsOutput.Cells(lngRowCount, 1)
    'we need to count how many rows there are in the usedrange so we know
    'where to paste into the output worksheet
    lngRowCount = lngRowCount + ws.UsedRange.Rows.Count + 1
    Next ws

End If

Next wb

End Sub