简体   繁体   English

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

[英]Merging dynamic ranges into one Range Excel or VBA

I am currently trying to take two ranges and combine them into one range. 我目前正在尝试将两个范围合并到一个范围中。 My ranges are dynamic because they change based off the date. 我的范围是动态的,因为它们根据日期更改。 For example, Suppose the two ranges I want to combine are A3:A10 and the other C7:C12. 例如,假设我要合并的两个范围是A3:A10和另一个C7:C12。 And every day it refreshes and moves the index by 1... so the new ranges are A4:A11 and C8:C13. 每天它刷新并将索引移动1 ...因此新的范围是A4:A11和C8:C13。 I want to combine the two into one range into a different column. 我想将两者合并为一个范围,放入另一列中。 I am assuming that this will have to be implemented in vba... however, I have been having minimal luck. 我假设这必须在vba中实现...但是,我的运气很小。 I have values that indicate what row number I want to make my ranges within my worksheet. 我有一些值指示要在工作表中进行范围调整的行号。 I've tried making VBA macros, but I have been having no luck. 我曾尝试制作VBA宏,但我一直没有运气。 I keep getting 9(the first term of the range I wanted) as my result and not a range, but I want to use the function to print the whole combined range. 我一直得到9(我想要的范围的第一项)作为我的结果,而不是范围,但是我想使用该函数来打印整个组合范围。 I have also thought about using Sub, but I am not very experienced in using Sub. 我也考虑过使用Sub,但是我对使用Sub的经验不是很丰富。

Here's what I have so far... Please let me know any suggestions or tips. 这是我到目前为止的内容...请让我知道任何建议或提示。

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

Thanks for the help 谢谢您的帮助

You should avoid the use of .Select/Activate . 您应该避免使用.Select/Activate You may want to see THIS . 您可能希望看到 Fully qualify your objects. 完全限定您的对象。

Also you have to use Set to assign ranges as shown below 另外,您还必须使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM