vba循环添加到string – 当前代码覆盖,而不是添加到单元格

我想添加到单元格,但我的代码保持覆盖自己。

例如

如果从第5列到第11列有一个值,我想把标题附加到特定的单元格(M列中的最后一个单元格)。

如果单元格e2 = 1月f2 = 2月g2 = 3月和e3 = 100 f3 = 40 g3 = 0

我想在M“State – Jan,Feb”的最后一行看到

目前代码以“State – Feb”结尾,因为它看起来代替了“Jan”而不是添加到它。

Dim iRow As Integer, iCol As Integer Dim sDesc as string, sDesc2 As String Dim wsEntry As Worksheet Dim wsUp As Worksheet Set wsEntry = Worksheets("Entries") Set wsUp = Worksheets("Sheet1") Dim lastrow As Long Dim sRange As Range For iRow = 6 To 7 lastrow = wsUp.Cells(Rows.Count, "A").End(xlUp).Row sDesc = wsEntry.Range("M" & iRow).Value wsUp.Range("M" & lastrow + 1).Value = sDesc For iCol = 5 To 11 If Cells(iRow, iCol) > "0" Then sEnt3 = wsEntry.Cells(5, iCol).Value sDesc2 = sDesc & sEnt3 & ", " wsUp.Range("M" & lastrow).Value = sDesc2 End If Next iCol 

string连接的问题可以通过不每次通过icol循环重置SDesc2的值,然后在循环结束后更新单元来解决:

 Dim iRow As Integer, iCol As Integer Dim sDesc as string, sDesc2 As String Dim wsEntry As Worksheet Dim wsUp As Worksheet Set wsEntry = Worksheets("Entries") Set wsUp = Worksheets("Sheet1") Dim lastrow As Long Dim sRange As Range For iRow = 6 To 7 'Qualify "Rows" lastrow = wsUp.Cells(wsUp.Rows.Count, "A").End(xlUp).Row sDesc = wsEntry.Range("M" & iRow).Value sDesc2 = "" For iCol = 5 To 11 'Qualify "Cells" (I have assumed you were referring to wsEntry) If wsEntry.Cells(iRow, iCol).Value > 0 Then ' Test numeric values, not strings 'Append comma only if something already present in the result If sDesc2 <> "" Then sDesc2 = sDesc2 & ", " End If sDesc2 = sDesc2 & wsEntry.Cells(5, iCol).Value End If Next iCol wsUp.Range("M" & lastrow + 1).Value = sDesc & sDesc2