繁体   English   中英

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

[英]VBA Excel Macro Copying One Column into Another Workbook

我有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

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

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

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

编辑:刚刚意识到你可能从那段代码中遗漏了什么。 在那里加一个“:”! 更改为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

我没时间测试这个。 会尽快做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM