How can I copy columns from one sheet to another with VBA in Excel?

前端 未结 5 1783
抹茶落季
抹茶落季 2020-12-09 17:39

I\'m trying to write a macro that copies the content of column 1 from sheet 1 to column 2 on sheet 2. This is how the module looks like but, when I run it, I get

相关标签:
5条回答
  • 2020-12-09 18:06

    If you have merged cells,

    Sub OneCell()
        Sheets("Sheet2").range("B1:B3").value = Sheets("Sheet1").range("A1:A3").value
    End Sub
    

    that doesn't copy cells as they are, where previous code does copy exactly as they look like (merged).

    0 讨论(0)
  • 2020-12-09 18:12

    I'm not sure why you'd be getting subscript out of range unless your sheets weren't actually called Sheet1 or Sheet2. When I rename my Sheet2 to Sheet_2, I get that same problem.

    In addition, some of your code seems the wrong way about (you paste before selecting the second sheet). This code works fine for me.

    Sub OneCell()
        Sheets("Sheet1").Select
        Range("A1:A3").Copy
        Sheets("Sheet2").Select
        Range("b1:b3").Select
        ActiveSheet.Paste
    End Sub
    

    If you don't want to know about what the sheets are called, you can use integer indexes as follows:

    Sub OneCell()
        Sheets(1).Select
        Range("A1:A3").Copy
        Sheets(2).Select
        Range("b1:b3").Select
        ActiveSheet.Paste
    End Sub
    
    0 讨论(0)
  • 2020-12-09 18:16

    The following works fine for me in Excel 2007. It is simple, and performs a full copy (retains all formatting, etc.):

    Sheets("Sheet1").Columns(1).Copy Destination:=Sheets("Sheet2").Columns(2)
    

    "Columns" returns a Range object, and so this is utilizing the "Range.Copy" method. "Destination" is an option to this method - if not provided the default is to copy to the paste buffer. But when provided, it is an easy way to copy.

    As when manually copying items in Excel, the size and geometry of the destination must support the range being copied.

    0 讨论(0)
  • 2020-12-09 18:23
    Private Sub Worksheet_Change(ByVal Target As Range)
      Dim rng As Range, r As Range
      Set rng = Intersect(Target, Range("a2:a" & Rows.Count))
      If rng Is Nothing Then Exit Sub
        For Each r In rng
          If Not IsEmpty(r.Value) Then
            r.Copy Destination:=Sheets("sheet2").Range("a2")
          End If
        Next
      Set rng = Nothing
    End Sub
    
    0 讨论(0)
  • 2020-12-09 18:25

    Selecting is often unnecessary. Try this

    Sub OneCell()
        Sheets("Sheet2").range("B1:B3").value = Sheets("Sheet1").range("A1:A3").value
    End Sub
    
    0 讨论(0)
提交回复
热议问题