[英]Excel VBA - Copy paste from/to sheets in list
I have a somewhat easy situation, but I lack the VBA knowledge to automate this process.我的情况有点简单,但我缺乏 VBA 知识来自动化这个过程。
In an Excel file called "Macro", I have a relation (column A and B) of sheets from two different workbooks I want to copy/paste values from/to.在名为“宏”的 Excel 文件中,我有两个不同工作簿中的工作表的关系(A 列和 B 列),我想从中复制/粘贴值。 I want to be able to run a macro that selects and opens the two workbooks, loops through the sheet list of workbook 1, copy the selected range (same for all sheets) and paste it in its correspondent sheet of workbook 2.
我希望能够运行一个宏来选择并打开两个工作簿,循环工作簿 1 的工作表列表,复制所选范围(所有工作表都相同)并将其粘贴到工作簿 2 的对应工作表中。
For example:例如:
I need to open Workbooks 1 and 2 (selected by the user), and copy values from sheet ABC to sheet XYZ, DEF to UVW...and so on我需要打开工作簿 1 和 2(由用户选择),并将值从工作表 ABC 复制到工作表 XYZ,将 DEF 复制到 UVW...等等
Workbook 1![]() |
Workbook 2![]() |
---|---|
Sheet ABC![]() |
Sheet XYZ![]() |
Sheet DEF![]() |
Sheet UVW![]() |
Hope this was clear.希望这很清楚。 Any help is appreciated!
任何帮助表示赞赏!
Put your table on sheet1 with upper left corner in cell A1.将表格放在 sheet1 上,单元格 A1 的左上角。 Configure the constant RNG_TO_COPY to your range.
将常量 RNG_TO_COPY 配置为您的范围。
Option Explicit
sub copyrange()
Dim RNG_TO_COPY As String
Dim ws As Worksheet, wb(2) As Workbook
Dim dict(2), filename(2) As String, s(2) As String
Dim iLastRow As Long, r As Long
Dim n As Integer, msg As String
' open workbooks and compile list of worksheet names
For n = 1 To 2
s(n) = GetFile(n)
If Len(s(n)) > 0 Then
Set dict(n) = CreateObject("Scripting.Dictionary")
Set wb(n) = Workbooks.Open(s(n))
For Each ws In wb(n).Sheets
dict(n).Add ws.Name, ws.Index
Next
Else
Exit Sub
End If
Next
' check data valid
Set ws = ThisWorkbook.Sheets(1)
iLastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
For r = 2 To iLastRow
For n = 1 To 2
s(n) = ws.Cells(r, n)
If Not dict(n).exists(s(n)) Then
msg = msg & vbCrLf & "'" & s(n) & "' in " & wb(n).Name
End If
Next
Next
' errors
If msg <> "" Then
MsgBox "Sheets do not exist" & msg, vbCritical
GoTo finish
End If
' copy ranges
For r = 2 To iLastRow
s(1) = ws.Cells(r, 1)
s(2) = ws.Cells(r, 2)
RNG_TO_COPY = ws.Cells(r, 3)
wb(1).Sheets(s(1)).Range(RNG_TO_COPY).Copy wb(2).Sheets(s(2)).Range(RNG_TO_COPY)
Next
MsgBox "Finished copying from " & wb(1).Name & " to " & wb(2).Name, vbInformation
finish:
wb(1).Close False
wb(2).Close True
End Sub
Function GetFile(n As Integer) As String
Dim f
Set f = Application.FileDialog(msoFileDialogFilePicker)
With f
.Title = "Select File " & n
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then Exit Function
GetFile = .SelectedItems(1)
End With
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.