选择行并复制到列

时间:2019-01-17 07:35:36

标签: excel vba

我想复制特定的一行,例如,我想在这张图片中选择杰克的分数

 image

现在我要像这样复制它们

here is the desired output

我问了社区,他们提供了很多帮助,我想到了这段代码:

Sub main()    
    Dim rangeSrc As Range, range1 As Range

    Set rangeSrc = Application.InputBox("Select src Range", "select src range", Type:=8) 'type 8 = range
    Set range1 = Application.InputBox("select des range", "select des range", Type:=8)

    If Not rangeSrc Is Nothing And Not range1 Is Nothing Then
        rangeSrc.Copy range1      
    End If     
End Sub

1 个答案:

答案 0 :(得分:0)

您快到了:

  1. 您需要.PasteSpecial Transpose:=True来转置数据。
  2. 我插入了一个错误处理程序,以便用户可以按“取消”按钮。
  3. 我重命名了您的变量,因为range1不是一个好的变量名。使用有意义的名称可以更轻松地读取和维护您的代码。

所以您最终得到了……

Option Explicit

Public Sub main()
    On Error Resume Next 'don't error on cancel button
    Dim rngSource As Range
    Set rngSource = Application.InputBox("Select src Range", "select src range", Type:=8) 'type 8 = range

    Dim rngDest As Range
    Set rngDest = Application.InputBox("select des range", "select des range", Type:=8)
    On Error GoTo 0 're-activate error reporting

    If Not rngSource Is Nothing And Not rngDest Is Nothing Then
        rngSource.Copy
        rngDest.PasteSpecial Transpose:=True
    End If
End Sub

如果您只想粘贴值而不设置格式,请使用…

rngDest.PasteSpecial Paste:=xlPasteValues, Transpose:=True

有关更多信息,请参见Range.PasteSpecial methodxlPasteType enumeration