定义两个范围,然后加入它们

时间:2015-10-13 09:14:51

标签: excel vba excel-vba

我目前想知道如何选择VBA中的范围,值范围,并希望有人可以协助下面的代码。

eoline = 50
first = 5
For i = 0 To eoline
multi = 2 * i + 1
a = Cells(first + 1, 1).Select
s1 = Range(Selection, Selection.End(xlDown)).select %select 1st range of values
b = Cells(first + 1, 2 * (i + 1)).Select
s2 = Range(Selection, Selection.End(xlDown)).select %select 2nd range of values
next i    

其实我想选择并复制s1& s2,我没有成功尝试

myval = Union(s1, s2).select
selection.copy

由于

2 个答案:

答案 0 :(得分:2)

像这样的东西

  1. 创建范围时使用Set
  2. 不要使用Select
  3. 当设置范围自下而上而不是选择向下时(如果有的话,将停在数据间隙处)
  4. Dim rng1 As Range
    Dim rng2 As Range
    Dim rng3 As Range
    
    Dim lngCnt As Long
    Dim lngCn2 As Long
    
    lngCnt = 5
    lngCnt2 = 2
    
    
    Set rng1 = Range(Cells(5, 1), Cells(Rows.Count, 1).End(xlUp))
    
    Set rng1 = Range(Cells(lngCnt + 1, 1), Cells(Rows.Count, 1).End(xlUp))
    Set rng2 = Range(Cells(lngCnt + 1, 2 * (lngCnt2 + 1)), Cells(Rows.Count, 2 * (lngCnt2 + 1)).End(xlUp))
    
    Set rng3 = Union(rng1, rng2)
    

答案 1 :(得分:0)

我找到了解决方案。这是我的问题的完整解决方案:

Dim s1, s2, myval As Range
eoline = 50
first = 5

multi = 2 * i + 1
a = Cells(first + 1, 1).Select
Set s1 = Range(Selection, Selection.End(xlDown))
b = Cells(first + 1, 2 * (i + 1)).Select
Set s2 = Range(Selection, Selection.End(xlDown))
Set myval = Union(s1, s2)
myval.Select