usedrange给出错误的列号

Sub testing() 'start searching for address Set wb = ThisWorkbook Set ws1 = wb.Sheets("Sheet1") Set ws2 = wb.Sheets("Sheet2") IncNum = Sheets("Sheet2").UsedRange.Columns.Count ExcNum = Sheets("Sheet1").UsedRange.Columns.Count InrNum = Sheets("Sheet2").UsedRange.Rows.Count Exrnum = Sheets("Sheet1").UsedRange.Rows.Count Set sheet1Table = Sheets("Sheet1").UsedRange Set sheet2Table = Sheets("Sheet2").UsedRange 'skip header For InrCounter = 2 To InrNum For ExrCounter = 2 To Exrnum If sheet1Table.Cells(InrCounter, 1) = sheet2Table.Cells(ExrCounter, 1) And sheet1Table.Cells(InrCounter, 2) = sheet2Table.Cells(ExrCounter, 2) And sheet1Table.Cells(InrCounter, 3) = sheet2Table.Cells(ExrCounter, 3) Then If IncNum = ExcNum Then Exit For Else Dim LastCofRowCounter, lastCofthisR As Integer lastCofthisR = sheet1Table.Cells(ExrCounter, Columns.Count).End(xlToLeft).Column For LastCofRowCounter = lastCofthisR + 1 To IncNum Sheets("Sheet1").Cells(ExrCounter, LastCofRowCounter) = Sheets("Sheet2").Cells(InrCounter, LastCofRowCounter) Next LastCofRowCounter End If ElseIf ExrCounter = Exrnum Then 'fid the last row of mastersheet lrowEx = Sheets("Sheet1").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row For counterCofLastR = 1 To IncNum Sheets("Sheet1").Cells(lrowEx + 1, counterCofLastR) = Sheets("Sheet2").UsedRange.Columns(1).Cells(InrCounter, counterCofLastR) Next counterCofLastR End If Next ExrCounter Next InrCounter End Sub the table looks like h1 h2 h3 h4 xxxx 

行ExcNum =表(“Sheet1”)。UsedRange.Columns.Count是给我9而不是4,我不知道为什么在这种情况下…我尝试在另一个工作表上,同样的表,它工作正常。

我试图打电话

  Sub ResetUsedRng() Application.ActiveSheet.UsedRange End Sub 

在执行所有的代码之前,但这不起作用。 我也读过你们联系的相关post,包括这个

  Private Sub Workbook_BeforeSave _ (ByVal SaveAsUI As Boolean, Cancel As Boolean) For Each Sh In ThisWorkbook.Worksheets x = Sh.UsedRange.Rows.Count Next Sh End Sub 

我叫Call Workbook_BeforeSave(True,False),这也没有工作。 想法?

对于更新.UsedRange属性,Excel是非常糟糕的。 如果您的工作表在某一时刻在列I应用了数据或格式,则可能是.UsedRange属性从未更新过。

由于.UsedRange在VBA中使用.UsedRange非常方便,我通常通过制定一个子表来检查表单中最后被占用的列和行,并删除 Sheet.UsedRange包含的任何额外的行和列。 这将强制更新该属性。

根据我的经验,唯一可靠的就是使用

 Lastcol = Cells.Find("*", [A1], , , xlByColumns, xlPrevious).Column Lastrow = Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row 

确定使用范围的最后一个单元格。 涉及UsedRangeSpecialCells(xlLastCell)End(xlUp)所有其他方法可能会给您错误的结果。

这两条线就是这样做的。 它使用specialcells来找出最后一列和最后一行。

  usedCol = ThisWorkbook.ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Column usedRow = ThisWorkbook.ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row 

欲了解更多信息,请访问微软网站

http://msdn.microsoft.com/en-us/library/office/ff196157.aspx