如何使用行号和列号创建范围并复制该范围?

时间:2016-02-23 12:59:15

标签: excel-vba macros vba excel

我正在尝试根据动态行和列号创建一个范围并复制该范围并将其粘贴到另一个范围。我能够获得行数和列数;但不确定如何创建范围并将其用于复制方法

Sub cut_paste()
    Set TS = ThisWorkbook.Sheets("Table_Schema")
    TS.Activate
    Dim rng As Range`enter code here`
    Dim str As String
    Dim frow As Integer
    Dim lRow As Integer

    lRow = Cells(Rows.Count, 1).End(xlUp).Row
    frow = Range("A1").End(xlDown).Row

    rng1 = "A" & frow
    rng2 = "H" & lRow
    str = """" & rng1 & ":" & rng2 & """"

    ' getting error on below line
    Set rng = Range(str)
    TS.Range(rng).Copy
End Sub

2 个答案:

答案 0 :(得分:1)

您不需要多个"来封装字符串,也不希望从范围(Range(rng))创建范围。 所以,有了改进

Sub cut_paste()
    Set TS = ThisWorkbook.Sheets("Table_Schema")
    Dim rng As Range
    Dim str As String, rng1 As String, rng2 As String
    Dim frow As Integer, lRow As Integer

    lRow = TS.Cells(Rows.Count, 1).End(xlUp).Row
    frow = TS.Range("A1").End(xlDown).Row

    rng1 = "A" & frow
    rng2 = "H" & lRow
    str = rng1 & ":" & rng2

    TS.Range(str).Copy
End Sub

答案 1 :(得分:0)

你过度使用字符串连接和Range object标识。

(identifier1# identifier_2# 23 4)

我使用With ... End With statement引用 Table_Schema 工作表作为所有单元格和范围引用的父级。

相关问题