excel VBA:从单元格函数设置范围

k5hmc34c  于 2022-12-01  发布在  其他
关注(0)|答案(3)|浏览(332)

我正在尝试使用Excel VBA创建sourcerange右侧一列的Range变量。

Dim targetRange as Range
Dim sourcerange as range

Set sourceRange = range("B1:B2") 'Works

Set targetRange = Range(cells(sourceRange.row, sourceRange.Column + 1)) 'does not work

Set targetRange = Range(Cells(2, 2)) 'does not work

有谁能解释一下为什么它不起作用吗?

jexiocij

jexiocij1#

用途

Sub Demo()
    Dim targetRange As Range, sourcerange As Range
    Set sourcerange = Range("B1:B2") 'Works
    Set targetRange = sourcerange.Offset(0, 1)
    Debug.Print targetRange.Address
End Sub
2hh7jdfx

2hh7jdfx2#

你的意思是这样的吗?

Dim sourceColumn As Long
Dim firstRow As Long
Dim lastRow As Long
Dim sourceRange As Range
Dim targetRange As Range

'Set source column number, and first + last row
sourceColumn = 2
firstRow = 1
lastRow = 3

'Set the source range, using the variables
Set sourceRange = Range(Cells(firstRow, sourceColumn), Cells(lastRow, sourceColumn))

'Likewise, set the target range, but using column number + 1
Set targetRange = Range(Cells(firstRow, sourceColumn + 1), Cells(lastRow, sourceColumn + 1))
yhqotfr8

yhqotfr83#

您必须始终引用该区域所属的工作表,即使该区域只包含一个单元格,也要设置起始单元格和结束单元格。

Set targetRange = YourSheet.Range(YourSheet.Cells(sourceRange.row, sourceRange.Column),YourSheet.Cells(sourceRange.row, sourceRange.Column+1))

相关问题