如果可能,我想知道如何做到这一点。我已将arrayC(26)定义为:
Dim arrayC(26) As String
arrayC(26) = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"
Dim i As Integer 'Position in the arrayC(26)
i = 1
根据另一个单元格的值,如果它的值为3,我想从A转到C.如果它的值为5,我想从A转到E.依此类推。
Dim j As Integer
j = 1
ReDim arrayCont(j) As Variant
让我们假设它从A到C。所以,我希望在arrayCont(j)中我有以下值“A,B,C”。然后我将转到Cells(8,“C”)以检查它是否等于arrayCont(j)中的值。如果是这样,我想从arrayCont(j)中删除该值。例如,考虑Cells(8,“C”)=“B”。然后我的arrayCont(j)将是“A,C”。我怎样才能做到这一点?
我创建的代码是:
Do While p <= sh1.Range("D6").Value
For p = 1 To sh1.Cells(6, "D").Value
If sh3.Cells(8, "C").Value = arrayC(p) Then
arrayCont(j) = arrayCont(j)
Else
arrayCont(j) = arrayC(p)
End If
Next p
j = j + 1
Loop
提前谢谢。
答案 0 :(得分:1)
首先,为了将括号内的所有字母添加到数组中的元素,数组必须是动态的(Dim arrayC As...
),而不是静态的({{1} })。此外,您要么使用Dim arrayC(26) As...
,要么在括号内的每个元素之前和之后添加Split
。
第二,以查找复制数组("
)内是否找到“C8”中的值,arrayCont
最多为i(= 3) ),我们使用Redim
来查找数组内匹配元素的索引。如果存在“匹配”,那么我们从数组中删除该元素。
第三次我正在使用名为“DeleteElementAt”的Application.Match
,它从数组中删除某个元素,依赖于您想要的数组的索引除去。
我的代码(已测试)
Sub
Sub DeleteElementAt 代码
Option Explicit
Sub SubArrayfromArray()
Dim arrayC As Variant
Dim i As Integer 'Position in the arrayC(26)
Dim arrayCont As Variant
' this is the way to put all the strings inside the brackets in an array (type Variant) in one line of code
arrayC = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z")
i = 3 ' i is the value of another worksheet cell
' copy original dynamic array to destination dynamic array
arrayCont = arrayC
' redim the copied array up to 3 (from 0 to 2)
ReDim Preserve arrayCont(0 To i - 1)
' value in Range C8 >> if "B" was found inside the arrayCont >> remove it from the array
If Not IsError(Application.Match(Range("C8").Value, arrayCont, 0)) Then
Call DeleteElementAt(Application.Match(Range("C8").Value, arrayCont, 0) - 1, arrayCont)
End If
' for debug only
'For i = LBound(arrayCont) To UBound(arrayCont)
' MsgBox "Array element " & i & " Value is " & arrayCont(i)
'Next i
' Edit 1: place arrayCont result in Cells(9, 3) >> Range("C9")
Range("C9").Resize(UBound(arrayCont) + 1, 1).Value = Application.Transpose(arrayCont)
End Sub