将值添加到已定义动态列中的最后一个空单元格

时间:2014-08-14 13:43:32

标签: database excel vba

我的模型从一张纸上取两个数字,将平均值添加到已定义列的最后一个单元格中的另一张纸上。我遇到的问题是,当我插入一个新列时,参考文献会被错过,并且我尝试使用一个宏来获取平均值2.在第二张纸上查找特定列3。将平均值粘贴到最后一个单元格。

请帮我解决这个问题。我一直试图让我的头围很长时间。

我的问题是我必须插入新列,并且我需要在向列中的最后一个空单元格添加值时保持引用动态。例如:如果我有作为col A的工资,和作为Col B的费用 - 在我现在的这个模型中,我现在放入.Cells(emptyRow,1)和.C​​ells(emptyRow,2),如果我在A之间插入一列和B参考文献1和2不起作用。无论如何,我可以解决这个问题,如果我添加一个新列,它不会搞乱宏中的引用? 谢谢。

这是我现在拥有的代码,但它并没有真正起作用 - 当我插入新列时,列定义的名称不会向右移动。

Sub demo()

    Dim expCol As Long, FirstEmptyRow As Long

    Range("B:B").Cells.Name = "expenses"

    expCol = Range("expenses").Column

    FirstEmptyRow = Cells(Rows.Count, expCol).End(xlUp).Row + 1

    Cells(FirstEmptyRow, expCol).Value = 123

End Sub

P.S。这里只是一个用于测试目的的示例。在我的模型中取代它的值是我在问题中谈到的平均值。

2 个答案:

答案 0 :(得分:0)

如果您的列有标题(我猜他们这样做),并且您的数据没有间隙,请使用 Range("1:1").Find(columnName).End(xlDown).Offset(1,0) = 123

如果列只能包含标题但没有值,则需要添加额外的检查,如果第二行不是空的。

答案 1 :(得分:0)

如果以这种方式创建命名范围(而不是您使用的Range.Cells.Name方式),那么在插入列时,引用将是动态的。现在,如果您稍后在代码中在A和B之间插入列,您仍然可以使用expColFirstEmptyRow来引用费用列中的第一个空单元格,它可能已移至工作表中,只要在每列插入后更新它们。

Sub Demo()
Dim expensesrng As Range
Dim Expenses As Range
Dim expCol As Long
Dim Exprng  As Range
Dim FirstEmptyRow  As Long

'set the original range to use for the expense column
Set expensesrng = Range(Range("B1"), Range("B1").End(xlDown))
'add the named range
ActiveWorkbook.Names.Add Name:="Expenses", RefersTo:=expensesrng
' create a variable to refer to the Expenses Range
Set Exprng = ActiveWorkbook.Names("Expenses").RefersToRange

expCol = ActiveWorkbook.Names("Expenses").RefersToRange.Column
FirstEmptyRow = Exprng.End(xlDown).Offset(1, 0).Row

Cells(FirstEmptyRow, expCol).Value = 123

'after inserting columns then you will have to get/update the column number
'of the expense named range and the first empty row before adding your new expense   
'data to it

Range("B:B").Insert Shift:=xlShiftToRight
expCol = ActiveWorkbook.Names("Expenses").RefersToRange.Column
FirstEmptyRow = expensesrng.End(xlDown).Offset(1, 0).Row

Cells(FirstEmptyRow, expCol).Value = 123

End Sub