Is it possible to create an 'input box' in VBA that can take a text selection with multiple lines as an input?

耗尽温柔 提交于 2019-12-11 15:26:35

问题


I am trying to create a macro that will filter out relevant information from some selected text (smaller than a page long). This information will then be used to fill out a MS-Word template.

I have been opening the selected texts via a .txt file however I feel it will improve workflow if it were possible to copy & paste the selected text into some form of an input box.

I have tried the following:

Dim text As String
text = InputBox("Enter selected text here:")

This however only accepts a string (a single line of text).

Thanks, Donfernanado


回答1:


As Rich Holton pointed out, you can create your own InputBox that supports the desired functionality:

First create a UserForm which looks like an InputBox. Mine is called CustomInputBox.

Set the MultiLine Property of the TextBox to True.

Example:

Then add some logic for the buttons and a Function to Show your Inputbox which takes some parameters like Prompt and Title:

Option Explicit

Private inputValue As String
Private Cancel As Boolean

Private Sub btnCancel_Click()
    Cancel = True
    Me.Hide
End Sub

Private Sub btnOK_Click()
    If Me.txtInput.Value <> "" Then
        inputValue = Me.txtInput.Value
    End If
    Me.Hide
End Sub

'This is the Function you are going to use to open your InputBox
Public Function Display(Prompt As String, Optional Title As String = "", Optional Default As String = "") As String
Cancel = False

Me.lblPrompt.Caption = Prompt

If Title <> "" Then
    Me.Caption = Title
Else
    Me.Caption = "Microsoft Excel"
End If

If Default <> "" Then
    Me.txtInput.Value = Default
Else
    Me.txtInput.Value = ""
End If

Me.txtInput.SetFocus
Me.Show vbModal

If Not Cancel Then
    Display = inputValue
Else
    Display = ""
End If
End Function

Now you are able to use your InputBox like this:

Dim text As String
text = CustomInputBox.Display("Enter selected text here:")


来源:https://stackoverflow.com/questions/43345287/is-it-possible-to-create-an-input-box-in-vba-that-can-take-a-text-selection-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!