【问题标题】:Direct reference to range Excel using VBA使用 VBA 直接引用范围 Excel
【发布时间】:2016-02-25 03:52:55
【问题描述】:

我在使用直接参考时遇到了问题。我试图在不使用选择或激活的情况下将值放入根工作簿。但是,如果需要将数据复制到的工作表未处于活动状态,我的代码会出错。如果工作表处于活动状态,则代码可以正常工作...

这是我的代码

Workbooks(root).Activate
Dim wb As Workbook
Set wb = Application.Workbooks(root)

wb.Sheets("d_eff_stress").Cells(1, n).Value = filename
wb.Sheets("d_eff_stress").Range(Cells(3, n), Cells(100, n)).Value = varray1
wb.Sheets("eff_stress").Cells(1, n).Value = filename
wb.Sheets("eff_stress").Range(Cells(3, n), Cells(100, n)).Value = varray2

解决方案:完全引用范围...我早就知道了

Workbooks(root).Activate
Dim wb As Workbook
Set wb = Application.Workbooks(root)

wb.Sheets("d_eff_stress").Cells(1, n).Value = filename
wb.Sheets("d_eff_stress").Range(wb.Sheets("d_eff_stress").Cells(3, n), wb.Sheets("d_eff_stress").Cells(100, n)).Value = varray1
wb.Sheets("eff_stress").Cells(1, n).Value = filename
wb.Sheets("eff_stress").Range(wb.Sheets("eff_stress").Cells(3, n), wb.Sheets("eff_stress").Cells(100, n)).Value = varray2

【问题讨论】:

标签: excel vba select reference


【解决方案1】:

您需要将工作表父级分配给范围内的Cells

wb.Sheets("d_eff_stress").Range(wb.Sheets("d_eff_stress").Cells(3, n), wb.Sheets("d_eff_stress").Cells(100, n)).Value

要减少打字,请使用With Blocks:

Workbooks(root).Activate
Dim wb As Workbook
Set wb = Application.Workbooks(root)

With wb.Sheets("d_eff_stress")
    .Cells(1, n).Value = filename
    .Range(.Cells(3, n), .Cells(100, n)).Value = varray1
End With

With wb.Sheets("eff_stress")
    .Cells(1, n).Value = filename
    .Range(.Cells(3, n), .Cells(100, n)).Value = varray2
End With

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2011-09-07
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 2019-04-06
    相关资源
    最近更新 更多