Excel VBA – 为什么我的单元格值不被追加?

我目前有一个脚本(见下文),将所使用的行中的每个单元格的内容添加到另一个工作表中的另一个单元格。 但是,这对于前3个单元格是有效的,但是由于某些原因,最后2个单元格不能工作。

Sub Ready_For_Infra() Dim i As Integer Dim k As Integer Dim ws1 As Worksheet Dim ws2 As Worksheet Set ws1 = Worksheets("InfraData") Set ws2 = Worksheets("ActionPlan") ws1.Cells.Clear For i = 2 To ws2.Cells(ws2.Rows.Count, 1).End(xlUp).Row Step 1 For k = 1 To ws2.Cells(1, ws2.Columns.Count).End(xlToLeft).Column With Worksheets("InfraData") If ws2.Cells(k, i).Value <> "" Then ws1.Range("A" & i).Value = ws1.Range("A" & i).Value & ws2.Cells(i, k).Value & Chr(10) End If End With Next k Next i MsgBox "Done" End Sub 

这是ws2(ActionPlan)中的数据,以防万一:

我正在传输的数据的示例

为了澄清,似乎并没有将细胞D2:F3附加到我所要求的细胞上。 有人能够build议为什么这可能是这样的吗?

试试这个代码:

 Sub Ready_For_Infra() Dim ws1 As Worksheet, ws2 As Worksheet Dim cell As Range Dim i As Long, lastrow As Long, lastcol As Long Dim str1 As String Set ws1 = Worksheets("InfraData") Set ws2 = Worksheets("ActionPlan") ws1.Cells.Clear With ws2 lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row lastcol = .Cells(1, .Columns.Count).End(xlToLeft).Column For i = 2 To lastrow str1 = "" For Each cell In .Range(.Cells(i, 1), .Cells(i, lastcol)) If cell.Value <> "" Then str1 = str1 & cell.Value & Chr(10) Next cell ws1.Range("A" & i).Value = str1 Next i End With MsgBox "Done" End Sub 

笔记:

  1. 使用For each循环稍快,然后For k=1 To lastcol
  2. 使用临时的stringvariablesstr1使得你的代码更快,因为在这种情况下,你只需要在ws1.Range("A" & i)单元格中写入结果值一次(使用操作内存总是比每次迭代在单元​​格中写入subresult )。