你没有正确地进行连接 -Letter
不应该在引号内。
这就是应该如何连接的方式。
Letter = "H"
LastRow = Cells(Rows.Count, 10).End(xlUp).Row
Set Rng = Range("J5:J" & LastRow)
For Each cell In Rng
If cell.Text <> "" Then
'ThisWorkbook.Sheets("Plg").Range("G6: N6").Value = Application.WorksheetFunction.Transpose(Rng)
ThisWorkbook.Sheets("Plg").Range("G6:" & Letter & "6").Value = Application.WorksheetFunction.Transpose(Rng) ' Giving error
End If
Letter = Chr(Asc(Letter) + 1)
Next cell
您也可以通过在开始时设置目标范围然后在循环的每次迭代中调整它的大小来做到这一点而无需连接。
Dim rngDst As Range
Dim rngSrc As Range
LastRow = Cells(Rows.Count, 10).End(xlUp).Row
Set rngSrc = Range("J5:J" & LastRow)
Set rngDst = Sheets("Plg").Range("G6:H6")
For Each cell In Rngsrt
If cell.Text <> "" Then
'ThisWorkbook.Sheets("Plg").Range("G6: N6").Value = Application.WorksheetFunction.Transpose(Rng)
rngDst.Value = Application.WorksheetFunction.Transpose(rngSrc) ' Giving error
End If
Set rngDst = rngDst.Resize(, rngDst.Columns.Count + 1)
Next cell
您也可以按照 BigBen 的建议使用 Cells 而不是 Range。
lngColNo = 8
LastRow = Cells(Rows.Count, 10).End(xlUp).Row
Set Rng = Range("J5:J" & LastRow)
For Each cell In Rng
If cell.Text <> "" Then
'ThisWorkbook.Sheets("Plg").Range("G6: N6").Value = Application.WorksheetFunction.Transpose(Rng)
With ThisWorkbook.Sheets("Plg")
.Range("G6", .Cells(6, lngColNo)).Value = Application.WorksheetFunction.Transpose(Rng) ' Giving error
End With
End If
lngColNo = lngColNo + 1
Next cell
这两个选项都比使用串联更可取,主要是因为使用当前代码更新列字母不会超出 Z 列。