0

我无法编写 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

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

4

1 回答 1

2

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

于 2021-05-24T15:49:08.997 回答