2014-09-19 148 views
-2

我是VBA的完全新手,因此请耐心等待。在Excel中使用VBA在列表中插入缺失值

我有一个缺少值的连续整数列表,也是一个缺失值列表。这些是A和B列。我想要做的是在列表中搜索比所选单元格中的值小的数字,插入一个低于该数字的单元格,并将选定的值放入新单元格,然后从“缺失值”列表中删除。

例如: 说我有,在列A中,列表:(1 2 3 5 6 9 10) 而在列B:(4 7 8) 我想什么能够做到在列B中选择其中包含“4”的单元格,并具有将会执行以下操作的子单元: 1.在列A中搜索列表以查找包含“3”的单元格 2.在A列下方的列A中插入一个单元格包含“3”,将余数向下移动 3.将“4”放入新列-A单元格 4.从列B中删除包含“4”的单元格,将余数向上移动

我已经过度简化它...我想用代码做这件事,因为在现实我的专栏 - 一个名单有近10,000个条目,而我的缺失值列B列表包含几百条。

我也许能够自己想象它,但是会感激一些我不需要花费数周来调整的东西。似乎如果我知道更多的VBA,它不会那么困难......总有一天!

回答

-1

这与使用指南您建议的数据为我工作:

Private Sub fixList() 
    ' Get reference to selected source cell 
    Dim criteriaCell As Range 
    Set criteriaCell = ActiveCell 

    ' Get value of that cell to be found in search column 
    Dim valueToLookFor As Long 
    valueToLookFor = criteriaCell.Value - 1 

    ' Get reference to matched cell in search column 
    Dim foundCell As Range 
    Set foundCell = Range("A:A").Find(valueToLookFor, , xlValues, xlWhole, , , False) 

    ' If the search didn't come back with nothing, the search criteria was found 
    If Not foundCell Is Nothing Then 

    ' Insert a cell below the found cell and populate it with the search data 
    foundCell.Select 
    foundCell.Offset(1, 0).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove 
    foundCell.Offset(1, 0).Value = criteriaCell.Value 

    ' Delete the original criteriaCell 
    criteriaCell.Select 
    criteriaCell.Delete xlUp 
    End If 
End Sub 
+0

就像一个魅力!感谢您不要简单地降低问题并继续前进。我也会研究代码,并学习我未来的可能,非常有帮助! – PwrCrdMfgr 2014-09-22 13:11:00

+0

哇!为什么选择正确的答案? – 2016-01-30 22:26:21

+0

我不知道...别人可能已经做到了。这不是我,我试图加入它,但显然我没有足够长的时间来这样做......没有足够的“声誉”?我不知道。无论如何,要知道你的代码仍然工作得很好,而且我感谢你的帮助! – PwrCrdMfgr 2016-02-01 16:06:22

0
Sub Interpolate() 
    Dim FirstR As Integer, FirstC As Integer 
    Dim r As Integer, c As Integer 
    FirstR = ActiveCell.Row 
    FirstC = ActiveCell.Column 
    For c = 0 To Selection.Columns.Count - 1 
     For r = 0 To Selection.Rows.Count - 1 
      If Len(Cells(FirstR + r, FirstC + c)) = 0 Then 
       Cells(FirstR + r, FirstC + c).Value = _ 
       (Cells(FirstR + r - 1, FirstC + c) + _ 
       Cells(FirstR + r + 1, FirstC + c))/2 
       With Cells(FirstR + r, FirstC + c) 
        .Font.Bold = True 
        .Font.ColorIndex = 3 
       End With 
      End If 
     Next r 
    Next c 
End Sub