复制多个Excel表单中的数据,并使用VBScript将其附加到单个Excel表单中

情况如下:

  1. 我有一个数据的Excel(.xls)文件。 (如A.xls
  2. 这个excel文件的数据在单个工作表上(表1)。
  3. 这个文件中的列数是固定的,即8
  4. 但是,包含数据的行数可能会不时变化。 (此文件不时被另一个程序更新)
  5. 现在,我有另一个Excel文件(例如B.xls )与类似的数据types,但不同于A.xls的内容。
  6. B.xls中的列也是8。 但是,包含数据的行数是未知的。

我想将A.xls的内容复制到第二行不包括列标题的第一行 ),并将其附加/粘贴到B.xls文件中,而不用覆盖B.xls上的现有数据。

考虑到所有这些细节,我想写一个VBScript来自动完成这个任务。

请帮忙。

非常感谢,提前。

它需要很多清理,但是这样的事情应该工作。 我会清理一下,然后进行编辑。

Sub CopyRows() ' Choose the name of the Second Workbook and last column. ' It must be in the same directory as your First Workbook. secondWorkbook = "B.xls" lastColumn = "H" ' A couple more variables currentWorkbook = ThisWorkbook.Name Workbooks.Open ThisWorkbook.Path & "\" & secondWorkbook ' In the First Workbook, find and select the first empty ' cell in column A on the first Worksheet. Windows(currentWorkbook).Activate With Worksheets(1).Columns("A:A") Set c = .Find("", LookIn:=xlValues) If Not c Is Nothing Then ' Select and copy from A2 to the end. secondAddress = Replace(c.Address, "$A$", "") Range("A2:" & lastColumn & CStr(CInt(secondAddress) - 1)).Select Selection.Copy End If End With ' Activate the Second Workbook Windows(secondWorkbook).Activate With Worksheets(1).Columns("A:A") Set c = .Find("", LookIn:=xlValues) If Not c Is Nothing Then ' Select and paste the data from First Workbook Range(c.Address).Select ActiveSheet.Paste End If End With End Sub 

更新 :这应该做的伎俩。 我也是第一次从错误的工作簿中复制出来的。 如果你有问题,请告诉我。

这是Macro Recoder可能为你写的东西。 你会以不同的方式出来。

打开录音。 打开A.xls和B.xls。 向下移动一行。 按Shift + End然后 ,然后按Shift + End + 。 然后按Ctrl + C来复制你的数据。 切换回B. 结束 + 按Ctrl + V进行粘贴。 closures录音。

你可以在Excel中logging。

Alt + TMR

然后Home键然后 。 停止录制。

看看Excel写了什么

 Selection.End(xlUp).Select 

或者如果您已经logging了转到对话框

 Application.Goto Reference:="R1C1" 

或者如果你有logging的Ctrl + Home

 Range("A1").Select 

转换为VBScript

在Excelmacroslogging器中logging步骤。 你必须重写它,因为它使用了一种vbs不支持的语法。

这适用于(我没有一个medium9) xlRangeAutoFormatAccounting4在vba中。

 Selection.AutoFormat Format:=xlRangeAutoFormatAccounting4, Number:=True, _ Font:=True, Alignment:=True, Border:=True, Pattern:=True, Width:=True 

所以首先在vba的对象浏览器中查看常量。 xlRangeAutoFormatAccounting4 = 17

然后在对象浏览器中查看函数,并查看函数定义的底部。

 Function AutoFormat([Format As XlRangeAutoFormat = xlRangeAutoFormatClassic1], [Number], [Font], [Alignment], [Border], [Pattern], [Width]) 

所以vba变成了vbs(而vbs在vba中也是如此)(正如你所看到的,你可以通过正确的方式来find正常的方式)

 Selection.AutoFormat 17, True, True, True,True, True, True 

所以你的代码变成了

 objXLWs.Range("A3").CurrentRegion.Select.AutoFormat 17, True, True, True,True, True, True