使用公式的用户范围输入

Using user range input for a formula

我正在尝试创建一个 VBA 代码,该代码将根据用户提供的范围和单元格将信息拉到连字符的左侧(最终是右侧)。 例如:

结果A和结果B也是我想要得到的。 我已经测试了我的代码中的所有内容,直到这一部分并且一切正常。如果我实际输入一个单元格地址(即 $D2 - 我将需要绝对列,但行相对,以便它随范围选择移动),整个事情就会起作用。我只是无法让它与“开始”变量的用户输入一起工作。我需要它作为用户输入,因为此代码将用于设置与此完全不同的工作表。我很有可能遗漏了一些明显的东西,但我没有看到它@_@。有什么建议吗?

**对于冗长的代码行提前表示歉意

Private Sub Seperate_XtoY_Click()

Dim iCol As Long
Dim iCount As Long
Dim i As Long
Dim Smaller As Range
Dim Bigger As Range
Dim Starting As Range

'Get number of columns that you want to insert with a user input box
iCount = InputBox(Prompt:="How many columns you want to add?")

'Get column NUMBER where you want to insert the new column
iCol = InputBox _
(Prompt:= _
"BEFORE which column do you want to add the new column(s)? (Enter the column number i.e A=1, B=2, C=3, etc)")

'loop to insert new column(s)
For i = 1 To iCount
    Columns(iCol).EntireColumn.Insert
Next i

'Makes range variable "Starting" equal to the user input of a range (in this case just 1 cell)
Set Starting = Application.InputBox("Select the FIRST cell of the Original Range of #'s", "Obtain Range Object", Type:=8)
'Makes range variable "Smaller" equal to the user input of a range (where the info will actually populate)
Set Smaller = Application.InputBox("Select a range", "Obtain Range Object", Type:=8)

Smaller.Formula = "=IF(ISNUMBER(SEARCH(""½"", & Starting.Address(0, ""$"") &)),""0.5"",IF(ISNUMBER(SEARCH(""¼"",& Starting.Address(0, ""$"") &)),""0.25"",IF(ISNUMBER(SEARCH(""¾"",& Starting.Address(0, ""$"") &)),""0.75"",LEFT( &Starting.Address(0, ""$"")&, FIND(""–"",& Starting.Address(0, ""$"")&)-1))))"

End Sub

事实证明,根据我上次的评论,我的想法是正确的。我 did 需要从引号中完全删除变量(然后重新启动它们),仔细检查我放置这些引号的位置,并使用不同版本的 .Address 函数来仅使我的专栏成为绝对参考。上面的所有其他代码行都很好,只是需要更改的最后一行。谢谢 @BigBen 给了我正确的方向。以新鲜的眼光看节目也很有帮助哈哈。

Smaller.Formula = "=IF(ISNUMBER(SEARCH(""½""," & Starting.Address(RowAbsolute:=False) & " )),""0.5"",IF(ISNUMBER(SEARCH(""¼"", " & Starting.Address(RowAbsolute:=False) & ")),""0.25"",IF(ISNUMBER(SEARCH(""¾"", " & Starting.Address(RowAbsolute:=False) & " )),""0.75"",LEFT( " & Starting.Address(RowAbsolute:=False) & " , FIND(""–"", " & Starting.Address(RowAbsolute:=False) & ")-1))))"

如果有人感兴趣的话,我也可以使用右侧功能:

Bigger.Formula = "=IF(ISNUMBER(SEARCH(""– ½""," & Starting.Address(RowAbsolute:=False) & ")),""0.5"",IF(ISNUMBER(SEARCH(""– ¼""," & Starting.Address(RowAbsolute:=False) & ")),""0.25"",IF(ISNUMBER(SEARCH(""– ¾""," & Starting.Address(RowAbsolute:=False) & ")),""0.75"",RIGHT(" & Starting.Address(RowAbsolute:=False) & ",LEN(" & Starting.Address(RowAbsolute:=False) & ")-FIND(""– ""," & Starting.Address(RowAbsolute:=False) & ")-1))))"

请注意对于可能想要使用我的代码变体的任何人,我使用了比典型连字符稍大的连字符(“-”与“–”)