我正在设置一个等于currentregion的范围。下面的代码有效,但是activate命令改变了我不想要的焦点。如果我删除了激活命令,则excel在最后一行崩溃。下面的代码在类模块和较大子的一部分中。有什么建议吗?
worksheets(SHT).activate 'stops the runtime error but changes sheet
With Worksheets(SHT)
With .Range(TBL2).CurrentRegion
.Cells = Data
End With
End With
答案 0 :(得分:1)
有很多代码丢失,但您可以使用类似的内容将2维变体数组(例如 Data )的内容传输到当前区域。
With Worksheets(SHT)
With .Range(TBL2).CurrentRegion
.Cells = Data
End With
End With
由于无法保证 Data 和.CurrentRegion的大小相同,因此可能会更好,
With Worksheets(SHT)
With .Range(TBL2).resize(ubound(Data, 1), ubound(Data, 2))
.Cells = Data
End With
End With
由于 Data 2-D数组的范围未知,因此很难更精确。
经过测试:
Sub collect_change_dump()
Dim SHT As String, TBL2 As String, v As Long, w As Long, Data As Variant
SHT = "Sheet1"
TBL2 = "D3"
With Worksheets(SHT)
With .Range(TBL2).CurrentRegion
Data = .Cells.Value
End With
For v = LBound(Data, 1) To UBound(Data, 1)
For w = LBound(Data, 2) To UBound(Data, 2)
Data(v, w) = "blah"
Next w
Next v
With .Range(TBL2).Resize(UBound(Data, 1), UBound(Data, 2))
.Cells = Data
End With
End With
End Sub