将dynamic范围合并到一个Range Excel或VBA中

我目前正在尝试将两个范围合并成一个范围。 我的范围是dynamic的,因为它们基于date而变化。 例如,假设我想组合的两个范围是A3:A10和另一个C7:C12。 每天刷新并移动索引1 …所以新的范围是A4:A11和C8:C13。 我想把这两个区域合并成一个不同的列。 我假设这将不得不在VBA实施…但是,我一直运气不大。 我有值表明我想在我的工作表中做我的范围的行号。 我试过制作VBAmacros,但我一直没有运气。 我一直得到9(我想要的范围的第一期)作为我的结果,而不是一个范围,但我想使用该function打印整个组合的范围。 我也想过使用Sub,但我不是很有经验的使用Sub。

这是我迄今为止…请让我知道任何build议或提示。

Function FiveYTwoY() Worksheets("India Data").Activate index5_90 = Cells(10, 2).Value '5Y 90 day index index5_yes = Cells(9, 2).Value '5Y yesterday index index2_90 = Cells(7, 2).Value '2Y 90 day index index2_yes = Cells(6, 2).Value '2Y yesterday index Dim range5 As Range Set range5 = Range(Cells(index5_90, 20), Cells(index5_yes, 20)) Dim range2 As Range Set range2 = Range(Cells(index2_90, 17), Cells(index2_yes, 17)) FiveYTwoY = Union(range2, range5) End Function 

谢谢您的帮助

您应该避免使用。select.Select/Activate 。 你可能想看到这个 。 完全限定你的对象。

你也必须使用Set来分配范围,如下所示

 Sub Sample() Dim range5 As Range, range2 As Range, FiveYTwoY As Range With Worksheets("India Data") index5_90 = .Cells(10, 2).Value '5Y 90 day index index5_yes = .Cells(9, 2).Value '5Y yesterday index index2_90 = .Cells(7, 2).Value '2Y 90 day index index2_yes = .Cells(6, 2).Value '2Y yesterday index Set range5 = .Range(.Cells(index5_90, 20), .Cells(index5_yes, 20)) Set range2 = .Range(.Cells(index2_90, 17), .Cells(index2_yes, 17)) Set FiveYTwoY = Union(range2, range5) With FiveYTwoY ' '~~> Do whatever you want with that range here ' End With End With End Sub