Excel: Listing Numbers In Between 2 Numbers

こ雲淡風輕ζ 提交于 2019-12-25 04:36:17

问题


I was wondering if anyone knew of a formula to list all the numbers between 2 values, so for example if cell F2 had 12 in it and G2 had 17 in it I'd like a formula that would show 13,14,15,16 In cell H2.

Thanks


回答1:


This cannot be done with an Excel worksheet function. You will need VBA for that. It can be done with a user-defined function (UDF).

The following code needs to be stored in a code Module. You need to right-click the sheet tab, select View Code. This will open the Visual Basic Editor. Click Insert > Module and then paste the following code:

Function InBetween(MyFirst As Integer, MyLast As Integer)
Dim foo As String
Dim i As Long
foo = MyFirst + 1
For i = MyFirst + 2 To MyLast - 1
    foo = foo & "," & i
Next i
InBetween = foo
End Function

Now you can use a formula like =InBetween(F2,G2) to produce the result you describe.

You need to save the file as a macro-enabled workbook with the XLSM extension. See screenshot for code and user defined function in action.




回答2:


Just because @teylyn said it couldn't be done with a formula - here is a formula based solution:

First you need to create the full list of numbers that you are likely to need as a string, this could be in another cell or my preference would be to create a named range.

So create a new named range called rng and in the Refers to text box add the following formula:

=",1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,"

For this solution to work you have to know the full range upfront, also note the leading and trailing comma.

Then enter the following formula into cell H2:

=SUBSTITUTE(LEFT(rng,FIND(","&G2&",",rng)+LEN(G2)),LEFT(rng,FIND(","&F2&",",rng) ),"")

To same the tedium of creating the number range string I used the following Powershell code to create and copy it to the clipboard:

1..20 -join ',' | % {"=`",$($_),`""} | clip.exe 

Just change the 20 in the above code for whatever range you require.



来源:https://stackoverflow.com/questions/31337844/excel-listing-numbers-in-between-2-numbers

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