使用变量作为参数复制范围

时间:2013-12-04 17:52:50

标签: excel-vba vba excel

我是VBA的新手,我遇到了Range语法问题以及可接受的参数。

此代码的目的如下:

  1. 用户将值输入到Sheet2上的单元格D5
  2. 用户使用按钮
  3. 激活代码
  4. 在“配置”表中搜索值
  5. 在找到值后复制相应的范围
  6. 粘贴范围回到Sheet2
  7. 我尝试复制粘贴的范围是一个以“Configs”表单上的选定单元格(D5)开头的块,并一直持续到找到一个空单元格。

    Sub search()
    
        Dim GCell As Range,
        Dim box As Integer
        Dim Avio As String
        Dim Sheet2 As Worksheet, Configs As Worksheet
        Dim rw1 As String, rw2 As String
    
        Set Configs = ActiveWorkbook.Sheets("Configs")
        Set Sheet2 = ActiveWorkbook.Sheets("Sheet2")
    
        Avio = Range("D5").Value
    
        Set GCell = Configs.Cells.Find(Avio)
    
        box = 0
    
        LoopX:
    
        box = box + 1
        If GCell.Offset(box, 0).Value = "" Then
    
        rw1 = GCell.Offset(1, -1).Address
        rw2 = GCell.Offset(box, 2).Address
    
        Configs.Range("rw1:rw2").Copy <-- this syntax doesnt seem to work...
        Sheet2.Range("Avio.Offset(1,0)").Paste <-- I know this is wrong, but I would like the range to be pasted just below the selected cell on Sheet2 
    
        Else: GoTo LoopX
        End If
    
    End Sub
    

1 个答案:

答案 0 :(得分:1)

这有帮助吗?

Sub search()

    Dim GCell As Range
    Dim box As Integer
    Dim Sheet2 As Worksheet, Configs As Worksheet
    Dim rw1 As String, rw2 As String

    Set Configs = ActiveWorkbook.Sheets("Configs")
    Set Sheet2 = ActiveWorkbook.Sheets("Sheet2")

    Dim rngAvio As Range
    Set rngAvio = Sheet2.Range("D5")

    Set GCell = Configs.Cells.Find(rngAvio.Value)

    box = 0
    Do While (GCell.Offset(box, 0).Value <> "")
        box = box + 1

        rw1 = GCell.Offset(1, -1).Address
        rw2 = GCell.Offset(box, 2).Address
        Configs.Range(rw1 & ":" & rw2).Copy rngAvio.Offset(1, 0)
    Loop

End Sub