在变量中存储范围

时间:2016-10-24 17:01:28

标签: excel vba excel-vba

我需要在变量中加入一系列值,即变量

tsPeriod(1) = (3, 4, 5)
tsPeriod(3) = (1, 2, 3).

我不知道要声明什么类型的变量以及如何执行此操作。我试过这样的事情:

Dim tsPeriod() as long
ReDim tsPeriod(nSub) as long
for i = 1 to nSub
   tsPeriod(i) = (tsStart(i), tsEnd(i))
next

但它没有那种方式工作,我有点失去了如何把它"范围"进入那个变量。 (如果第一个值是3而第二个值是6我希望变量检索(3,4,5,6))

以下是代码的一部分:

Dim wb As Workbook
Set wb = ThisWorkbook

Dim subjects As Worksheet
Set subjects = wb.Sheets("Subject")

Dim nSub As Integer, nRooms As Integer

nSub= subjects.Cells(Rows.Count, 1).End(xlUp).value

Dim tsStart() As Long
ReDim tsStart(nSub) As Long

For i = 1 To nSub
    tsStart(i) = subjects.Cells(i + 1, 3).value
Next

Dim tsBusy() As Long
ReDim tsBusy(numDis) As Long

For i = 1 To nSub
    tsBusy(i) = subjects.Cells(i + 1, 4).value
Next

Dim tsEnd() As Long
ReDim tsEnd(nSub) As Long

For i = 1 To nSub
    tsEnd(i) = tsStart(i) + tsBusy(i) - 1
Next

'Here's where im having trouble
Dim tsPeriod() As Long
ReDim tsPeriod(nSub) As Long

For i = 1 To nSub
    tsPeriod(i) = (tsStart(i), TsEnd(i))
Next

2 个答案:

答案 0 :(得分:1)

没有内置"范围" VBA中的方法:您需要标注所需大小的数组并使用循环填充它。您可以创建一个函数来执行此操作:

Function RRange(startNum, endNum)
   Dim rv() as long, i
   Redim rv(1 to (endnum-startnum)+1)
   for i = startNum to endNum
       rv((i-startNum)+1) = i
   next i
   RRange = rv
End Function

然后:

For i = 1 To numDis
    tsPeriod(i) = RRange(tsStart(i), TsEnd(i))
Next

答案 1 :(得分:0)

您可以结合使用Application.TransposeEvaluate和工作表 - ROW功能来实现目标。

对于

tsPeriod(i) = (tsStart(i), TsEnd(i))

只需使用

tsPeriod(i) = Application.Transpose(Evaluate("=ROW(" & tsStart(i) & ":" & tsEnd(i) & ")"))

从第一个值到最后一个值获取数组。 要获得以逗号分隔的字符串,请将其放在Join这样的

tsPeriod(i) = Join(Application.Transpose(Evaluate("=ROW(" & tsStart(i) & ":" & tsEnd(i) & ")")), ",")
如果一切正常,

Join也适用于测试,因为您可以使用Debug.Print