将数据从一个工作簿复制到另一个工作簿

时间:2015-06-14 23:38:51

标签: excel vba excel-vba

我试图将数据从一个工作簿复制到另一个工作簿。我一直存在的问题是我复制的工作簿每次都会更改名称。

我粘贴数据的工作簿将保持不变。我已经知道如何获取数据我只是有问题切换回工作簿我正在复制数据。

这是我到目前为止所做的。

Sub grabdata()

Application.ScreenUpdating = False
Application.DisplayAlerts = False

Dim w As Workbook

w = ActiveWorkbook

lrow = ThisWorkbook.Sheets("Month").Cells(Rows.Count, 3).End(xlUp).Row
LoopEnd = lrow - 16

LRowTxtTab = 2

For x = 32 To LoopEnd

' Grabs Metrics from Month tab (This is the grab data from workbook and will       change everytime

ThisWorkbook.Sheets("Month").Select
GridEnd = x + 16
Range("D" & x, "V" & GridEnd).Copy


(this is the workbook that will stay the same all the time)
Workbooks("NRBSrub").Activate
Workbooks("NRBSrub").Worksheets("Sheet5").Select

Range("E" & LRowTxtTab).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=True

' Grabs assocaited brands per metrics copied over above
BrandName = ThisWorkbook.Sheets("Month").Range("A" & x)
Sheets("Sheet5").Range("B" & LRowTxtTab, "B" & LRowTxtTab + 18) = BrandName

LRowTxtTab = LRowTxtTab + 19
x = x + 17

Next x

' Grabs FY time frames for FISC_MO column
LRowTxtTab = ThisWorkbook.Sheets("Sheet5").Cells(Rows.Count, 
5).End(xlUp).Row
ThisWorkbook.Sheets("Month").Range("D2:V2").Copy
Sheets("Sheet5").Range("C2").PasteSpecial Paste:=xlPasteValues,   
Operation:=xlNone, _
SkipBlanks:=False, Transpose:=True

Application.ScreenUpdating = True`enter code here`
Application.DisplayAlerts = True

End Sub

1 个答案:

答案 0 :(得分:1)

  

我只是遇到了切换回工作簿的问题,我正在从

复制数据

使用Set

Dim w As Workbook: Set w = ActiveWorkbook

然后你可以在这样的工作簿之间切换:

w.Activate

或使用with方法

With w
    lrow = .Sheets("Month").Cells(Rows.Count, 3).End(xlUp).Row
    'do whatever you need with w
End with
With Workbooks("NRBSrub")
    'do whatever you need with Workbooks("NRBSrub")
End With