根据命名范围的单元格输入设置范围

Set the range based on a cell input which a named range

VBA 有点新手。我正在尝试将值从源传播sheet 复制到目标传播sheet。在目标 spreadsheet 中,我有一个导入设置 sheet,其中有一列包含我想从源 spreadsheet 复制的命名范围,我还有一列包含复制数据目的地的命名范围。

我在定义目标范围和源范围时遇到了问题。我希望脚本遍历每一行并将目标和源范围设置为导入设置 sheet 中相关列中指定的命名范围,并将数据从源复制到目标。

任何帮助将不胜感激。

Public Sub grabIRR()   
Dim temp_workbook As Excel.Workbook
Dim filepath As String
Dim filename As String
Dim source_range As String
Dim dest_range As String
Dim IRR_Row As Integer

Application.Calculation = xlCalculationManual
Set temp_workbook = Workbooks.Open(filename:=link_to_IRR, ReadOnly:=True)
Application.Calculation = xlCalculationManual

shtPrivateEquity.Cells.ClearContents

For IRR_Row = 15 To 110
    dest_range = Worksheets("import_settings").Range(IRR_Row, 11).Value.RefersToRange
    source_range = Worksheets("import_settings").Range(IRR_Row, 9).Value.RefersToRange
    shtPrivateEquity.Range(dest_range).Value = temp_workbook.Names(source_range).RefersToRange.Value
Next IRR_Row
On Error GoTo 0

Application.Calculation = xlCalculationAutomatic
temp_workbook.Close savechanges:=False

结束子

我认为将名称作为字符串而不是范围对象使用会更容易。

试试这个:

For IRR_Row = 15 To 110
    dest_range_name = Worksheets("import_settings").Cells(IRR_Row, 11).Value
    source_range_name = Worksheets("import_settings").Cells(IRR_Row, 9).Value
    shtPrivateEquity.Range(dest_range_name).Copy Destination := temp_workbook.Range(source_range_name)
Next IRR_Row

注意我改了一些变量名,把不合法的Range(row, column)改成了Cells(row, column)