[英]Loop through cells and add values into an array then display into activecell in VBA
我已經為此苦苦掙扎了一段時間,我需要幫助。 我是 vba 的新手,希望能得到一些關於這個問題的指導。 我的電子表格已設置,因此我在單元格 a2 中並正在讀取 b2 中的值,該值是一個整數,它告訴我存在多少個補充配置文件 (sups)。 假設數字 3 在 b2 中。 然后我希望 c2 下方的 2 行也在 c3 和 c4 中輸入一些文本(角色)。
在 a2 上,我正在讀取 b2 以獲取補充配置文件的數量,然后循環以在 a2 上顯示在 c2、c3 和 c4 中找到的角色。 這可能會改變,因為在某些情況下只有 2 個角色或 3 個角色,依此類推。
為此,我編寫了以下代碼:
Sub testarray()
Dim sups As Integer
Dim role, resultrole As String
Dim test() As String
role = ActiveCell.Offset(i, 2).Value
sups = ActiveCell.Offset(0, 1).Value
i = 0
Do While i <= sups
test() = Split(role)
i = i + 1
ActiveCell.Value = test()
Loop
End Sub
問題是我只顯示了第 c2 行,而不是下面的所有內容。 我希望 a2 顯示值 c2、c3 和 c4。 我將針對多行運行此代碼,以便關聯角色。
查看我的代碼和電子表格的圖片,其中包含我正在閱讀的值
您只會看到單元格 A 中顯示的第一個值,因為您從未讓代碼移動到活動單元格以外的任何位置。 您確實有一個循環,但它只是遍歷數字。
下面的代碼將遍歷 B 列中的所有單元格,並將角色寫入與 sups 編號存儲位置相鄰的 A 列中。 它將寫入由|
分隔的內容 . 您可以根據需要進行編輯。
我也拿出了一個Array的使用。 當你使用它時,它不會給你你想要的 - 這是一個串聯的值。 您可以將單元格范圍存儲到一個數組中並循環遍歷數組以將單元格值寫入 A 列,但鑒於您的問題,這似乎沒有真正的優勢。
Sub testarray()
Dim sups As Long, x As Long
Dim role As String
Dim lRow As Long
lRow = Range("B" & Rows.Count).End(xlUp).Row
Dim cel As Range
For Each cel In Range("B2:B" & lRow)
role = ""
If Len(cel) Then
sups = cel
For x = 1 To sups
role = role & "|" & cel.Offset(x - 1, 1)
Next
role = Mid(role, 2, Len(role) - 1)
cel.Offset(, -1) = role
End If
Next
End Sub
一些小的調整以使其盡可能接近原始版本。 我不喜歡使用ActiveCell
,但@ScottHoltzman 有一個解決方案。
Sub testarray()
Dim sups As Integer, i&
Dim role, resultrole As String
Dim test As String
role = ActiveCell.Offset(i, 2).Value
sups = ActiveCell.Offset(0, 1).Value
i = 0
Do While i <= sups - 1
If i = 0 Then
test = ActiveCell.Offset(i, 2)
Else
test = test & ", " & ActiveCell.Offset(i, 2)
End If
i = i + 1
Loop
ActiveCell.Value = test
End Sub
這應該一次與一個ActiveCell 屬性一起使用。
Sub testarray()
Dim sups As Long, roles As Variant
With ActiveCell
sups = .Offset(0, 1).Value
ReDim roles(sups - 1)
For sups = LBound(roles) To UBound(roles)
roles(sups) = .Offset(sups, 2)
Next v
.Cells = Join(roles, Chr(10))
End With
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.