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

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

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

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)

尝试…

 xlLastCol = ActiveSheet.UsedRange.Columns.Count 

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

我没有testing,但都应该工作。

让我知道如果你有任何问题,我可以花一些时间自己testing它!

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

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

根据@brettdj发布的代码确实有效。 最后一列附近有一个“1”。 它可能已经在那里服务于macros观或某些function,但我不相信它仍然被使用。