【问题标题】:Dynamic discontinuous excel ranges in VBAVBA中的动态不连续excel范围
【发布时间】:2016-08-12 15:30:27
【问题描述】:

如何动态扩展需要复制到另一张工作表的两列中的行数?

首先,我确定需要包含并存储在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

【问题讨论】:

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

标签: vba excel


【解决方案1】:
.Range("B2:B102,G2:G102").copy

可以写成

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

【讨论】:

    【解决方案2】:

    不使用.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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多