Hi Tom
Is the following possible?  I have a column of numbers that inform a chart in a workbook.  The column of numbers must contain at least one instance of the following numbers otherwise I will get an “invalid reference” error message: “7”, “8”, “9”, “10” and “11”.

Is it possible to write a piece of code that will look in the column and check if there is an instance of any of these numbers?
If anyone of these numbers is missing I would like it placed at the bottom of the row of numbers. So if Column “B” does not have an instance of the number “8”, I would like the number “8” to be placed at the bottom of the list of numbers.

Again, if this task is beyond the scope of what is normally expected please let me know.  At the very least it would be nice if the task is achievable with code.

Thanks in advance

Chris Mitchell

Chris Mitchell,

I believe this will do what you want.

Sub abc()
Dim icol As Long, lastrow As Long, i As Long
Dim scol As String

scol = "B"
icol = Range(scol & ":" & scol).Column

lastrow = Cells(Rows.Count, icol).End(xlUp).Row
For i = 7 To 11
 If Application.CountIf(Cells(1, icol).Resize(lastrow, 1), i) = 0 Then
   lastrow = lastrow + 1
   Cells(lastrow, icol).Value = i
 End If
End Sub

It works on the active sheet.   If you need to specify the sheet name:

Sub abcSheetName()
Dim icol As Long, lastrow As Long, i As Long
Dim scol As String
Dim sh as worksheet

set sh = worksheets("Sheet2rng")
scol = "B"
icol = sh.Range(scol & ":" & scol).Column

lastrow = sh.Cells(sh.Rows.Count, icol).End(xlUp).Row
For i = 7 To 11
 If Application.CountIf(sh.Cells(1, icol).Resize(lastrow, 1), i) = 0 Then
   lastrow = lastrow + 1
   sh.Cells(lastrow, icol).Value = i
 End If
End Sub

Tom Ogilvy  
About Excel
This topic answers questions related to Microsoft Excel spreadsheet (or workbook) stand-alone or Mircrosoft Office Excel including Excel 2003, Excel 2007, Office 2000, and Office XP. You can get Excel help on Excel formulas(or functions), Excell macros, charting in Excel, advanced features, and the general use of Excel. This does not provide a general Excel tutorial nor the basics of using a spreadsheet. It provides specific answers to using Microsoft Excel only. If you do not see your Excel question answered in this area then please ask an Excel question here


All Answers

Answers by Expert:

Ask Experts


Tom Ogilvy


Selected as an Excel MVP by Microsoft since 1999. Answering Excel questions in Allexperts since its inception in 2001. Able to answer questions on almost all aspects of Excel's internal capabilities. If seeking a VBA solution, please specify that in your question itself so I give you the answer you want. [Excel has weak protection - if you are distributing an application, I don't answer questions on how to protect your project from your users.]


Extensive experience.

Master of Science (MS) degree Operations Research (ORSA)

Awards and Honors
Microsoft MVP in Excel.

©2017 About.com. All rights reserved.