2016-08-12 63 views
3

如何动态扩展需要复制到另一个工作表的两列中的行数?VBA中的动态不连续excel范围

首先,我确定的行我需要包括和数量店totrows

Dim totrows As Integer 
With ThisWorkbook.Worksheets("Sheet1") 
    totrows = .Range("A" & .Rows.Count).End(xlUp).Row 
End With 

接下来,我想延长的利益(“B”和“G”)两个列,以便该范围包括totrows行。对于静态例如,如果totrows = 100然后我会:

With ThisWorkbook.Worksheets("Sheet1") 
    .Range("B2:B102,G2:G102").copy 
End With 

我然后将它们粘贴到我的第二片材与:

ThisWorkbook.Worksheets("Sheet2").Range("A2").Paste 
+0

谢谢!我一直在尝试'&'而没有运气 - 我一直把逗号放在引号之外(!) – Bendy

回答

3
.Range("B2:B102,G2:G102").copy 

可以写成

.Range("B2:B" & totrows & ",G2:G" & totrows).Copy 
1

另一种不使用.Copy.Paste的方法是:

Sub Copy() 
    Dim wb As Workbook 
    Dim wsCopy As Worksheet 
    Dim wsPaste As Worksheet 
    Dim totrows As Integer 

    Set wb = Workbooks("Book1.xlsm") 
    Set wsCopy = wb.Worksheets("Sheet1") 
    Set wsPaste = wb.Worksheets("Sheet2") 
    totrows = wsCopy.Range("A" & wsCopy.Rows.Count).End(xlUp).Row 

    wsPaste.Range("A1:B" & totrows) = wsCopy.Range("A2:A" & totrows, "G2:G" & totrows).Value 


End Sub 

这样你直接把值放入你想要的Range