如何将命名范围从一个工作簿复制到特定单元格中的另一工作簿?

时间:2019-01-02 16:25:53

标签: excel vba excel-vba

下面是我的原始代码。我正在尝试更改代码,以便添加/删除新的列/行不会影响新创建的工作簿。我决定使用名称范围来避免代码被破坏。 (我知道如何在名称管理器中创建新范围)有人知道如何调整代码?

Dim WS As Worksheet
Dim Rng As Range
Dim myWs As Worksheet
Set myWs = ThisWorkbook.Sheets("MASTER")
Set Rng1 = myWs.Range("A1:AJ4")
Set Rng2 = myWs.Range("A85:AJ104")
Application.Workbooks.Add
Set WS = Application.ActiveSheet
Rng1.Copy Destination:=WS.Range("A1:AJ4")
Rng2.Copy Destination:=WS.Range("A5:AJ50")

1 个答案:

答案 0 :(得分:0)

您需要将要使用的每个工作簿和工作表调暗。

Dim wb1 as Workbook, wb2 as Workbook, ws1 as Worksheet, ws2 as Worksheet
Dim xrow as long, arrData() as variant

Set wb1 = Workbooks("Book1")
Set ws1 = wb1.Worksheets("Sheet1")

Set wb2 = Workbooks("Book2")
Set ws2 = wb2.Worksheets("Sheet2")

请注意,这仅在两个工作簿都打开的情况下有效。

我也建议将数据从每个单元格复制到数组,而不是复制范围。这样我得到的错误更少。

ApplicationScreenUpdating = False

ws1.Activate

'where n is the number of rows you want to copy
for x = 1 To n
arrData[x - 1] = ws1.Cells(x, 1).value
next x

ws2.Activate

for i = 1 to n
ws2.Cells(i, 1).value = arrData[i - 1]
next i

ApplicationScreenUpdating = True