2015-10-13 48 views
2

我目前想知道如何選擇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

像這樣的事情

  1. 使用Set當您創建範圍
  2. 不要使用Select
  3. 當設置範圍尋找自下而上,而不是選擇向下(這將在數據差距停止,如果你有一個)

代碼

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) 
+0

非常感謝您的反饋,因爲看到另一種實現相同任務的方式總是很有趣。 – owner

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 
+0

您應該編輯您的問題,而不是張貼無答案。 –

+0

當然。但爲了避免造成混淆,最好依靠本節「發佈自己的答案」,並在發現之後添加一些更新,因爲這可能對其他人有益。這裏的更新確實奏效。乾杯 – owner