如何在范围分配中使用变量

时间:2013-10-24 21:19:25

标签: excel vba variables excel-vba range

我想使用我可以传递给SUB的变量,用于将数组从一个工作表复制到另一个工作簿中的另一个工作表。没有变量,这对我很有用:

Dim RNG1 as Range, RNG2 as Range
Sub CopyRange()
    Set RNG1 = Workbooks("Program.xlsm").Sheets("Input").Range("G9:G19")
    Set RNG2 = Workbooks("Data.xlsx").Sheets("Reformatted").Range("A3:A13")
    RNG1.Copy RNG2
End Sub

我希望能够将“Data.xlsx”作为变量传递给SUB。我尝试过使用String变量,但还没有找到解决方案。

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

Sub CopyRange(wbName as string)
    Dim RNG1 as Range, RNG2 as Range 'these need only to be Local variables
    Set RNG1 = Workbooks("Program.xlsm").Sheets("Input").Range("G9:G19")
    Set RNG2 = Workbooks(wbName).Sheets("Reformatted").Range("A3:A13")
    RNG1.Copy RNG2
End Sub

使用:

CopyRange "Data.xlsx"

答案 1 :(得分:0)

这个怎么样?

Dim RNG1 As Range, RNG2 As Range
Sub test()
    Call CopyRange(Workbooks("Data.xlsx"))
End Sub

Sub CopyRange(ByRef wb As Excel.Workbook)
    Set RNG1 = Workbooks("Program.xlsm").Sheets("Input").Range("G9:G19")
    Set RNG2 = wb.Sheets("Reformatted").Range("A3:A13")
    RNG1.Copy RNG2
End Sub