如何为Range变量指定单元格范围

时间:2016-07-29 07:04:05

标签: vba excel-vba excel

我的环境:MS Excel 2013

我想将代码范围分配给我的范围变量,代码低于

Dim strSourceFile As String
Dim wbSource As Workbook

strSourceFile = "D:\csv1.csv"
Set wbSource = Workbooks.Open(strSourceFile)
Set rngY = wbSource.Sheets(1).Range(Cells(2, RefCol), Cells(LastSource, RefCol))

尝试将值分配给rngY时,我在最后一行收到错误。

Run-time error '1004':
Application-defined or object-defined error

1 个答案:

答案 0 :(得分:1)

Cells(2, RefCol)正在引用活动工作表上的单元格。您必须限定所有范围对象。

示例1:

Set rngY = wbSource.Sheets(1).Range( wbSource.Sheets(1).Cells(2, RefCol),  wbSource.Sheets(1).Cells(LastSource, RefCol))

示例2:

With wbSource.Sheets(1)
    Set rngY = .Range( .Cells(2, RefCol), .Cells(LastSource, RefCol))
End With