VBA Excel: Assigning range values to a new range

﹥>﹥吖頭↗ 提交于 2019-12-12 20:24:09

问题


I am having trouble assigning values from one workbook range to a range in my current workbook. When I assign my range using Range("A1:C1") this code works fine, however when my range is defined using Range(Cells(1,1),Cells(1,3)) the function fails:

Sub CopyRange()
    Dim inputExcel As Excel.Application, BookA As Workbook
    Path_A = ThisWorkbook.Path & "\Book_A.xlsx"
    Set inputExcel = New Excel.Application
    Set BookA = inputExcel.Workbooks.Open(Path_A, ReadOnly:=True)

    'THIS WORKS:
    ThisWorkbook.Sheets(1).Range("A1:C1").Value = _
    BookA.Sheets(1).Range("A1:C1").Value

    'THIS DOESN'T WORK:
    ThisWorkbook.Sheets(1).Range(Cells(1, 1), Cells(1, 3)).Value = _
    BookA.Sheets(1).Range(Cells(1, 1), Cells(1, 3)).Value
End Sub

I know this must be a simple syntax issue but I haven't been able to figure it out. How can I get the Range assignments using "Cells" to work?


回答1:


you've gotta qualify the Cells calls with a worksheet object too:

ThisWorkbook.Sheets(1).Range(ThisWorkbook.Sheets(1).Cells(1, 1), ThisWorkbook.Sheets(1).Cells(1, 3)).Value = _
    BookA.Sheets(1).Range(BookA.Sheets(1).Cells(1, 1), BookA.Sheets(1).Cells(1, 3)).Value

for contiguous ranges like that you can also use Resize:

ThisWorkbook.Sheets(1).Cells(1, 1).Resize(, 3).Value = _
        BookA.Sheets(1).Cells(1, 1).Resize(, 3).Value



回答2:


I think ultimately you are going about this in not the best way to solve the problem. You have object.object.object.object notation in your code, which is cumbersome and hard to interpret and fix.

If you define some more variables, the code will be easier to troubleshoot and solve your problem:

Dim myAddr as String 'A string to represent the Address of the range
myAddr = Cells(1,1).Address & ":" & Cells(1,3).Address

ThisWorkbook.Sheets(1).Range(myAddr).Value = BookA.Sheets(1).Range(myAddr).Value


来源:https://stackoverflow.com/questions/20637835/vba-excel-assigning-range-values-to-a-new-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!