excel代码在第一个未使用的列中插入数据

时间:2012-03-21 15:57:17

标签: excel excel-vba vba

我目前正在为数据透视表生成的自动化编写一些例程。 为了使数据透视表工作,我想插入的列必须与现有数据连续。如何让Excel在第一个未使用的列中插入数据?

我在网上找到了以下参考资料:

Function xlLastCol(Optional WorksheetName As String) As Long

 ' Author:  MWE
 ' http://www.vbaexpress.com/kb/getarticle.php?kb_id=418

 '       finds the last populated col in a worksheet

If WorksheetName = vbNullString Then WorksheetName = ActiveSheet.Name
With Worksheets(WorksheetName)
    On Error Resume Next
    xlLastCol = .Cells.Find("*", .Cells(1), xlFormulas, _
    xlWhole, xlByColumns, xlPrevious).Column
    If Err <> 0 Then xlLastCol = 0
End With

End Function

但它总是返回一些奇怪的数字,绝对不是最后使用的列。 (第一个未使用的列将只是最后一次使用的列+ 1)

3 个答案:

答案 0 :(得分:0)

...试

xlLastCol = ActiveSheet.UsedRange.Columns.Count

xlLastCol = ActiveSheet.Cells.Find(What:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByColumns).Column

我没有测试,但两者都应该有用。

如果您有任何问题,请告诉我,我可以花一些时间亲自测试一下!

答案 1 :(得分:0)

要获取第1行中的最后一个可用列,请使用此代码

LastCol = Sheets("Sheet1").Cells(1, Columns.Count).End(xlToLeft).Column + 1

答案 2 :(得分:0)

根据@brettdj发布的代码确实有效。最后一列附近有一个“1”。可能一直在那里服务宏或什么功能,但我不相信它仍然使用。