2017-04-19 83 views
0

我的Excel文件非常龐大,我發現原因在於未使用的列。如果我刪除它們,文件具有正常大小。 未使用的列只是空格或至少顯示爲空格。但是,它們必須包含一些內容。 如何找出什麼以及如何將UsedRange重置爲包含內容的實際列數?Excel VBA使用的列

我試過如下:

myLastCol = _ 
    .Cells.Find("*", after:=.Cells(1), _ 
    LookIn:=xlFormulas, lookat:=xlWhole, _ 
    searchdirection:=xlPrevious, _ 
    searchorder:=xlByColumns).Column 

而且還

myLastCol=ActiveSheet.UsedRange.Columns.Count 

雙方將返回值16383。有什麼建議麼?這怎麼可能發生(我確定它與我寫的宏有關)?

+0

你有一行是**總是**填充了一個數據範圍內的數據?你有沒有一個文本總是填滿你的數據? – Jeeped

+2

我很困惑。你想修復你的子程序每次運行它的錯誤還是你想修復子程序的錯誤,所以它不會出錯?我會推薦後者。 – Jeeped

+0

這種情況經常發生在將錯誤的格式或類似行爲應用於整列或行時,而無關行*看起來像是空白的時候,它們實際上已將某些樣式或格式應用於它們,並認爲它們位於'UsedRange'中。如果你的問題是因爲代碼一遍又一遍地執行,當你點擊它時,它會根據我上面寫的內容計算,檢查和重構你的代碼。否則,只需刪除額外的行|專欄和繼續與生活:) –

回答

0

難道你不能只刪除未使用的列?如果是這樣的解決方案呢?

Sub DeleteUnusedColumns() 

     Dim colRange As Range 
     Dim c As Long 

    'Define the target range 
     Set colRange = ActiveSheet.UsedRange 

    'Iterate through the columns 
     For c = colRange.Columns.Count To 1 Step -1 

    'If the column is empty then you can delete it 
      If Application.CountA(Columns(c).EntireColumn) = 0 Then 
      Columns(c).Delete 
      End If 

    'Increment the counter down 
     Next c 
    End Sub 

End Sub