在公式中使用输入框

问题描述 投票:0回答:1

我试图让用户通过单击两个单元格来输入它们,然后将单元格值而不是实际值应用到公式中,这样它就可以在每一行上工作,直到工作表末尾。现在,用户将选择 D2 和 G2(它们总是会变化并且永远不会是相同的两列),并且它应该连接在一起作为“IN-IA”,然后第 3 行将是“IN-AL”等。

有没有办法让 ST1 和 ST2 等于单元格而不是实际值,然后一直填充到数据末尾?

Dim ST1 As Variant
Dim ST2 As Variant

ST1 = Application.InputBox("Select the origin state", Type:=8)
ST2 = Application.InputBox("Select the destination state", Type:=8)

ActiveCell.FormulaR1C1 = "=CONCATENATE(Trim(" & ST1 & "),""-"",Trim(" & ST2 & "))"

它在做什么: enter image description here

我想要它做什么: enter image description here

excel vba input formula inputbox
1个回答
0
投票

你必须以稍微不同的方式处理这个问题,因为这是一个棘手的情况。

当用户按下

Cancel
时,
Application.InputBox
将返回
False
,这是一个
Boolean
值。如果用户选择一个范围,那么
Application.InputBox
将返回
Range
。你不能使用

Dim ST1 As Variant    
ST1 = Application.InputBox("Select the origin state", Type:=8)

因为如果您选择一个范围,那么您需要使用

Set
。当用户取消时这会产生问题。

出于类似的原因,你甚至不能使用

Dim ST1 As Range
并保留它。处理这个问题的一种方法是使用
On Error Resume Next

同样正如@BigBen提到的,你必须使用

.Address
属性来获取范围的地址。

这就是你正在尝试的吗?

Sub Sample()
    Dim ST1 As Range
    Dim ST2 As Range
    
    '~~> Pad it with OERN
    On Error Resume Next
    Set ST1 = Application.InputBox("Select the origin state", Type:=8)
    Set ST2 = Application.InputBox("Select the destination state", Type:=8)
    On Error GoTo 0
    
    '~~> Check if Application.InputBox returned a range. If not
    '~~> Then it means user presses cancel
    If ST1 Is Nothing Or ST2 Is Nothing Then
        MsgBox "user Cancelled"
    Else
        '~~> Now you can use ST1 and ST2 as Range objects
        MsgBox "You selected: " & ST1.Address(False, False) & " and " & ST2.Address(False, False)
        '~~> ActiveCell.FormulaR1C1 = "=CONCATENATE(Trim(" & ST1 & "),""-"",Trim(" & ST2 &
    End If
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.