提问人:HummBird 提问时间:9/30/2023 更新时间:9/30/2023 访问量:45
收集在一个单元格中组合的列范围值,后跟逗号,并以 & 分隔符结尾
Collect column range value combined in one cell followed by comma and end with & seperator
问:
我正在尝试在一个单元格中获取收集组合值,后跟逗号并以 &
列范围结尾:AM4:AM20 可能带有值或空白。
我需要将此值与逗号和 & 分隔符组合在一起收集
AM4 = ABCD1
AM5 = ABCD2
AM6 = ABCD3
AM7 = ABCD4
AM8 = “” AM9 =“”
例如,BB4 = ABCD1、ABCD2、ABCD3 和 ABCD4
我试过这个代码
Sub GetPipeData()
Dim ws As Worksheet
Dim lastRow As Long
Dim cell As Range
Dim collectedValues As String
Dim addComma As Boolean
' Set the worksheet containing the values
Set ws = ThisWorkbook.Sheets("INPUT")
' Find the last used row in column AM
lastRow = ws.Cells(ws.Rows.Count, "AM").End(xlUp).Row
' Initialize the collectedValues variable
collectedValues = ""
addComma = False ' Initialize the flag to not add a comma
' Loop through the cells in column AM from row 4 to the last used row
For Each cell In ws.Range("AM4:AM20" & lastRow)
' Check if the cell is not empty
If Not IsEmpty(cell.Value) Then
' If addComma is True, add a comma before the value
If addComma Then
collectedValues = collectedValues & ", "
End If
' Add the value to the collectedValues variable
collectedValues = collectedValues & cell.Value
' Set addComma to True for the next iteration
addComma = True
End If
Next cell
' Print the collected values in cell BB4
ws.Range("BB4").Value = collectedValues
End Sub
预期结果
**BB4 = ABCD1, ABCD2, ABCD3 & ABCD
**
请帮我完成这个任务。谢谢你:)
答:
1赞
Black cat
9/30/2023
#1
随着添加的 Do...循环,您可以获得所需的结果。
Sub GetPipeData()
Dim ws As Worksheet
Dim lastRow As Long
Dim cell As Range
Dim collectedValues As String
Dim addComma As Boolean
' Set the worksheet containing the values
Set ws = ThisWorkbook.Sheets("INPUT")
' Find the last used row in column AM
lastRow = ws.Cells(ws.Rows.Count, "AM").End(xlUp).Row
' Initialize the collectedValues variable
collectedValues = ""
'addComma = False ' Initialize the flag to not add a comma
' Loop through the cells in column AM from row 4 to the last used row
For Each cell In ws.Range("AM4:AM20")
' Check if the cell is not empty
If Not IsEmpty(cell.value) Then
' If addComma is True, add a comma before the value
If addComma Then
collectedValues = collectedValues & ", "
End If
' Add the value to the collectedValues variable
collectedValues = collectedValues & cell.value
' Set addComma to True for the next iteration
addComma = True
End If
Next cell
'This code added
pos = 1
Do While InStr(pos + 1, collectedValues, ",") <> 0
pos = InStr(pos + 1, collectedValues, ",")
Loop
If pos<>1 Then collectedValues = Left(collectedValues, pos - 1) & " &" & Mid(collectedValues, pos + 1)
'Till here
' Print the collected values in cell BB4
ws.Range("BB4").value = collectedValues
End Sub
评论
0赞
HummBird
9/30/2023
非常感谢,为 1 个查询提供了 2 个解决方案。快乐。我学到了。
2赞
Jos Woolley
9/30/2023
#2
或者你可以只使用一个工作表公式:
=LET(
Φ,AM4:AM20,
SUBSTITUTE(TEXTJOIN(", ",,Φ),", "," & ",MAX(1,SUM(N(Φ<>""))-1))
)
评论