我怎样才能将值之间的空白空间添加到VBA数组?

我通过循环表单中的单元格(originalWS)在vba中创build一个数组。 我们假设单元格(2,5)到(2,12)具有以下内容:

(2,5)Item (3,5)Type (4,5)Nominal Diameter (5,5)Lead . . . (12,5)For Use with End Blocks 

因此,当我循环下面的代码,我得到一个数组,看起来像这样:

[项目,types,公称直径,导程,…,用于端块]。

不过,我想在我的数组中的每个值之间添加两个空的空格。 所以它看起来像这样:

[Item,“”,“”,Type,“”,“”,“公称直径”,“”,“”,“Lead”,“

 ReDim propertyArr(1, lastRow) For i = 1 To lastRow propertyArr(1, i) = originalWS.Cells(i + 1, 5).Value Debug.Print propertyArr(1, i) Next 

我已经尝试循环到数组的最终总大小,所以(lastRow * 3),并向前走了3.但是,我很难搞清楚我将如何重置我的原始WS.cells(我,5)值,以便它们是连续的。

换句话说,当我循环步进3我的价值观将是:

 propertyArr(1,1) = originalWS.Cells(2,5).value propertyArr(1,4) = originalWS.cells(5,5).value propertyArr(1,7) = originalWS.cells(8,5).value 

我怎样才能循环,以便我每两个地方在我的数组中存储值,而我从表单中的连续列表中获取值。

我可以做到这一点,而无需添加额外的空行的方式来添加两个空的空间之间的原始循环中的每个值,而不必添加额外的空行?

或者,第一次创build我的数组后,我可以在每个值之间添加两个空的空格吗?

这应该做的伎俩,

 Dim lRowNo As Long lRowNo = lastRow * 3 ReDim propertyArr(1, lRowNo) For i = 1 To lRowNo If i Mod 3 = 1 Then propertyArr(1, i) = originalWS.Cells(i + 1, 5).Value Else propertyArr(1, i) = "" End If Debug.Print propertyArr(1, i) Next 

就像是:

 Sub ytrewq() Dim propertyArr(), lastRow As Long Dim originalWS As Worksheet Set originalWS = ActiveSheet lastRow = 5 ReDim propertyArr(1, 2 * lastRow) For i = 1 To 2 * lastRow Step 2 propertyArr(1, i) = originalWS.Cells(i + 1, 5).Value propertyArr(1, i + 1) = "" Debug.Print propertyArr(1, i) Next End Sub 

UNTESTED

您也可以展开一些循环来更有效地做到这一点。 请注意,对于每个迭代, i不是递增1 ,而是3

 Public Sub test() Dim lastRow As Long lastRow = 6 Dim lastIndex As Long lastIndex = lastRow * 3 ReDim propertyArr(1 To lastIndex) Dim i As Long For i = 1 To lastIndex Step 3 propertyArr(i) = CInt(i / 3) propertyArr(i + 1) = vbNullString propertyArr(i + 2) = vbNullString Next End Sub 

或者没有循环

 Dim ws As Worksheet Set ws = Sheets(1) propertyarr = Join(Application.Transpose(ws.Range("E1:E5")), ","""","""",") 

放回arrays

 propertyarr = Split(Join(Application.Transpose(ws.Range("E1:E5")), ",,,"), ",") 

我想出了答案。 我没有正确更新我需要的单元格。 见下面的代码:

 count = 3 lastIndex = lastRow * 3 ReDim propertyArr(1, lastIndex) For i = 1 To lastIndex Step 3 propertyArr(1, i) = originalWS.Cells((count - 1), 5) count = count + 1 Next