从同一文件夹复制工作簿之间的单元格范围

时间:2016-12-03 10:12:58

标签: vba excel-vba excel

我目前有:

Sub Ranger()
Dim rng As Range
Dim WB1 As Workbook, WB2 As Workbook, ActiveWB As Workbook
Dim WS1 As Worksheet, WS2 As Worksheet
Dim FName As String

FName = "General Text"
Set WB1 = ThisWorkbook
Set WS1 = WB1.Sheets("Sheet1")
Set WB2 = Workbooks.Open(FileName:=FName)
Set WS2 = WB2.Sheets(1)

With WS2
    Set rng = .Range(Range("A1"), Range("A5"))
    End With

With WS1
    rng.Copy .Cells(1, 1)
    End With

WB2.Close
End Sub

其目的是将新打开的工作簿中的范围A1:A5复制到原始工作簿(ThisWorkbook)中。它目前打开第二个工作簿,但不会将任何内容复制到第一个工作簿中。也没有错误,我想避免在设置WB1 / WB2时使用特定名称,因为WB2可能是.xls或.xlsx

1 个答案:

答案 0 :(得分:1)

试试这个,它对我有用:

Sub Ranger()

  Dim rng As Range
  Dim WB2 As Workbook
  Dim FName As String

  FName = "D:\Tuchanka\Temp\pelda.xlsx"
  Set WB2 = Workbooks.Open(Filename:=FName)

  ThisWorkbook.Worksheets(1).Range("A1:A5").Value = WB2.Worksheets(1).Range("A1:A5").Value

  WB2.Close
End Sub

在你的情况下使用变量和语句是毫无意义的,因为它们不仅使你的代码更简单,更容易阅读,而且还会增加许多乱码并使你的代码看起来过于复杂。只有在需要时才使用它们。