我正在使用此代码在现有已关闭的工作簿中提取2列,如何设置混合它们?
Sub CopyColumnToWorkbookA()
Dim sourceColumn As Range, targetColumn As Range
Set sourceColumn = Workbooks.Open(ThisWorkbook.Path & "\res\res.xlsx", False, True).Worksheets(1).Columns("A")
Set targetColumn = Workbooks("Caltoday.xlsm").Worksheets(2).Columns("A")
sourceColumn.Copy Destination:=targetColumn
End Sub
Sub CopyColumnToWorkbookB()
Dim sourceColumnb As Range, targetColumnb As Range
Set sourceColumnb = Workbooks.Open(ThisWorkbook.Path & "\res\res.xlsx", False, True).Worksheets(1).Columns("B")
Set targetColumnb = Workbooks("Caltoday.xlsm").Worksheets(2).Columns("B")
sourceColumnb.Copy Destination:=targetColumnb
ActiveWorkbook.Close
End Sub
我不想两次打开工作簿,但是我试图混合它们没有成功,有什么想法吗?
答案 0 :(得分:1)
无需关闭两次,只需合并一个子。下面比必要的更“罗嗦”,但我保持这样,所以你可以学习并看到一种方法来做到这一点。
Sub copyColumn()
Dim sourceWB As Workbook
Dim sourceWS As Worksheet
Set sourceWB = Workbooks.Open(ThisWorkbook.Path & "\res\res.xlsx", False, True)
Set sourceWS = sourceWB.Worksheets(1)
Dim i As Long
For i = 1 To 2
sourceWS.Columns(i).Copy Workbooks("Caltoday.xlsm").Worksheets(2).Columns(i)
Next i
sourceWB.Close False
Application.CutCopyMode = False
End Sub
或者只是做
SourceWS.Columns("A:B").Copy Workbooks("Caltoday.xlsm").Worksheets(2).Columns("A:B")
答案 1 :(得分:1)
同时获取两列。然后使用您的副本同时粘贴它们。
Set sourceColumn = Workbooks.Open(ThisWorkbook.Path & "\res\res.xlsx", False, True).Worksheets(1).Columns("A:B")
Set targetColumn = Workbooks("Caltoday.xlsm").Worksheets(2).Columns("A:B")
答案 2 :(得分:0)
我的0.02美分
Sub copyColumn()
With Workbooks.Open(ThisWorkbook.Path & "\res\res.xlsx", False, True) ‘ open and reference source workbook
.Worksheets(1).Columns("A:B").Copy Destination:=Workbooks("Caltoday.xlsm").Worksheets(2).Columns("A:B") ‘ copy referenced workbook sheet 1 columns A: B and paste into Caltoday workbook sheet 2 same columns
.Close False ‘close referenced workbook discarding changes
End With
End Sub