如何在 vba 中用变量写入范围

How to write range with variable in vba

我无法编写 vba 代码,其中提到的范围具有随每次迭代而变化的变量。

这是一个代码

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

我希望我的代码像引用语句一样执行,但它给出了一个错误。

您没有正确进行连接 - 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 列。