在excel中编辑长字符串

时间:2013-10-21 08:54:57

标签: excel-vba vba excel

我尝试完成的任务: 我的单元格中有长串,想要编辑它们。之后我想把它们写回那个单元格。

我已经尝试过了: 我试图将文本复制到单词bullitpoint分离并将文本写回excel单元格。但这有点像用大锤敲打坚果。我也知道输入框和msgbox,但我无法解决我的问题。

我在寻找什么: 我正在寻找一个点击事件,将我的文本放入弹出窗口,我可以在其中编辑文本并将其写回发布事件的单元格或其他方式来编辑我的字符串。

1 个答案:

答案 0 :(得分:1)

<强>逻辑:

  1. 创建Userform而不是Inputbox。这样您就可以编辑文本了。 MsgBox是不可能的,因为您将无法编辑任何内容。
  2. Worksheet_Change启动用户表单,然后您可以在那里编辑文本,最后将其写回工作表。
  3. 基本准备:

    打开VBA编辑器并插入用户表单。添加TextBoxCommandButton。它可能看起来像这样。

    enter image description here

    代码:将其粘贴到用户窗体的代码中

    Private Sub UserForm_Initialize()
        With TextBox1
            .MultiLine = True
            .WordWrap = True
            .ScrollBars = fmScrollBarsVertical
            .EnterKeyBehavior = True
        End With
    End Sub
    
    Private Sub CommandButton1_Click()
        Unload Me
    End Sub
    

    代码:将其粘贴到相关的工作表代码区域

    '~~> Length of characters
    Const nChars As Long = 2
    
    Private Sub Worksheet_Change(ByVal Target As Range)
        Dim sString As String
    
        On Error GoTo Whoa
    
        '~~> Check if there was a Paste/Autofill done
        If Target.Cells.CountLarge > 1 Then Exit Sub
    
        Application.EnableEvents = False
    
        '~~> Check if the length is more than 2
        If Len(Target.Value) > nChars Then
            '~~> Set the userform's textbox text
            With UserForm1
                .TextBox1.Text = Target.Value
                .Show
                '~~> Get the value back to the sheet
                Target.Value = .TextBox1.Text
            End With
        End If
    
    Letscontinue:
        Application.EnableEvents = True
        Exit Sub
    Whoa:
        MsgBox Err.Description
        Resume Letscontinue
    End Sub
    

    代码在行动:

    enter image description here

    填写完文本后,我们进行相关更改(我将第二句移至新行)并按下Update按钮。

    enter image description here

相关问题