将整列复制到文本框中

时间:2015-03-13 19:31:51

标签: excel excel-vba vba

我需要在 Sheet4 上的 TextBox 中复制 Sheet1 的所有列L 。<登记/> 我试着这样做:

Sub ToTB()
    Sheets("Sheet4").TextBoxes("TextBox 2").Text = Sheets("Sheet1").Range("L:L").Text
End Sub

然后出现这条消息:

  

应用程序定义或对象定义的错误

有什么建议吗?

2 个答案:

答案 0 :(得分:5)

这是一些有点直接的东西。如果您已经拥有 TextBox ,只需要添加一系列单元格中的值:

Sub Test()
    Dim srng As Range
    Dim sWs As Worksheet: Set sWs = Sheets("Sheet1")
    Set srng = sWs.Range("L1", sWs.Range("L" & sWs.Rows.Count).End(xlUp))
    With Sheets("Sheet4").Shapes("Textbox 2").OLEFormat.Object
        .Text = Join(Application.Transpose(srng), vbCrLf)
    End With
End Sub

或者如果你希望它像Gary发布的那样添加:

Sub Test()
    Dim sWs As Worksheet, dWs As Worksheet
    Set sWs = Sheets("Sheet1"): Set dWs = Sheets("Sheet4")

    Dim dRng As Range, sRng As Range
    Set dRng = dWs.Range("A1:A10") 'change to suit
    Set sRng = sWs.Range("L1", sWs.Range("L" & sWs.Rows.Count).End(xlUp))

    With dWs.Shapes.AddTextbox(msoTextOrientationHorizontal, _
        dRng.Left, dRng.Top, dRng.Width, dRng.Height).OLEFormat.Object
        .Text = Join(Application.Transpose(sRng), vbCrLf)
    End With
End Sub

答案 1 :(得分:2)

使用 Sheet4

enter image description here

运行此宏:

Sub CoverRange()
    msg = ""
    Sheets("Sheet4").Activate
    For Each r In Intersect(ActiveSheet.UsedRange, Range("L:L"))
        msg = msg & vbCrLf & r.Text
    Next r

    Sheets("Sheet1").Activate
    Dim L As Long, T As Long, W As Long, H As Long
    Set r = Range("B9:B20")
    L = r.Left
    T = r.Top
    W = r.Width
    H = r.Height
    With ActiveSheet.Shapes
        .AddTextbox(msoTextOrientationHorizontal, L, T, W, H).Select
    End With
    Selection.Characters.Text = msg
End Sub

将在 Sheet1

中生成此内容

enter image description here