VBA Excel宏将一列复制到另一个工作簿中

时间:2014-01-10 00:18:18

标签: excel vba excel-vba

我有2个工作簿,我正在尝试找到一种方法将列从wb1复制到wb2。我知道我可以复制/粘贴,但想法是做一些事情,这样我的老板可以点击宏,一切都填充。

我一直在尝试另一个问题中遇到的代码:

Sub Import()

Dim sourceColumn As Range
Dim destColumn As Range

Set sourceColumn = Workbooks("C:\Documents and Settings\********\My Documents\*********.xlsm").Worksheets(2).Columns("BL")
Set destColumn = Workbooks("C:\Documents and Settings\********\My Documents\*********.xlsm").Worksheets(2).Columns("A")

sourceColumn.Copy Destination = destColumn

End Sub

当我运行它时,我收到“下标超出范围”错误。

源列包含依赖于其他列的公式,目标列为空,但即使我在带有小数字的虚拟工作簿上运行它,我也会遇到相同的错误。

我在这里缺少一些超级基本的东西吗?

1 个答案:

答案 0 :(得分:2)

编辑:刚刚意识到您可能从这段代码中遗漏了什么。在那里加一个“:”!更改为destination:=Workbooks("....,它应该可以正常工作。

额外细节:使用函数参数时,必须添加“:”才能向计算机指定您不评估相等性,而是进行参数赋值。


(陈旧的,华丽的回答) 我认为这是你想要做的;这个脚本可能会做你想要的。但是这种风格不会被保留。

Sub yourSub()

Application.ScreenUpdating = False 'Disables "Screen flashing" between 2 workbooks

Dim colA As Integer, colB As Integer
Dim rowA As Integer, rowB As Integer
Dim wbA As Workbook, wbB As Workbook

Set wbA = ThisWorkbook
Set wbB = Workbooks.Open("C:/YourFilePath/YourFile.xls")

colA = 1 'Replace "1" with the number of the column FROM which you're copying
colB = 1 'Replace "1" with the number of the column TO which you're copying

rowA = 1 'Replace "1" with the number of the starting row of the column FROM which you're copying
rowB = 1 'Replace "1" with the number of the row of the column TO which you're copying

wbA.Activate
lastA = Cells(Rows.Count, colA).End(xlUp).Row 'This finds the last row of the data of the column FROM which you're copying
For x = rowA To lastA 'Loops through all the rows of A
    wbA.Activate
    yourData = Cells(x, colA)
    wbB.Activate
    Cells(rowB, colB) = yourData
    rowB = rowB + 1 'Increments the current line of destination workbook
Next x 'Skips to next row

Application.ScreenUpdating = True 'Re-enables Screen Updating

End Sub

我还没来得及测试。会尽快做。