2017-10-19 82 views
0

我期待從位於文件夾中的多個文本文件提取信息,將它們放在單個工作表上,並且只保留每個工作表的相關信息。我在刪除不需要的行時遇到問題,我正在對行進行着色,以便可以對相關信息進行排序。代碼如下。謝謝提取相關信息Excel VBA

Private Sub CommandButton1_Click() 

Dim ws As Worksheet 
Dim rng As Range 
Dim lastRow As Long 
Dim myCell As Range 

iPath = "C:\Users\dbutler\Desktop\Folder_1\" 'Imports the text files from Folder address 
iFile = Dir(iPath & "*.txt") 
Do While Len(iFile) 
Sheets.Add , Sheets(Sheets.Count), , iPath & iFile 
iFile = Dir 
Loop 

'Selects every sheet but Command 
For Each ws In ThisWorkbook.Worksheets 
    If ws.Name <> "Command" Then 

     lastRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row 
     Set rng = ws.Range("A1:A" & lastRow) 
     'filter and delete all rows 
     For Each myCell In rng 

'Delete rows if they do not contain the below values 
      If Not (myCell Like "*10570*" Or _ 
       myCell Like "*10571*" Or _ 
       myCell Like "*10572*" Or _ 
       myCell Like "*11503*" Or _ 
       myCell Like "*10308*" Or _ 
       myCell Like "*11324*" Or _ 
       myCell Like "*18368*" Or _ 
       myCell Like "*13369*" Or _ 
       myCell Like "*15369*" Or _ 
       myCell Like "*10814*" Or _ 
       myCell Like "*22306*" Or _ 
       myCell Like "*12009*" Or _ 
       myCell Like "*15088*" Or _ 
       myCell Like "*72216*") Then 

       myCell.EntireRow.Delete 


      End If 
      Next myCell 


End If 
Next ws 

End Sub 
+0

究竟是什麼問題?太多行被刪除?錯誤信息?還要別的嗎? – Jochen

+0

它不會刪除不相關的信息,或者任何東西。如果我將myCell.EntireRow.Delete更改爲myCell.Interior.Color = RGB(255,0,0),它會爲行着色,所以我想知道是否有刪除行的不同過程。最初我使用了Autofilter功能,但它不允許我有兩個以上的標準。 –

回答

0

.entirerow.delete是正確的。我認爲你的問題在於當你開始從頂端刪除時數據的轉移。

嘗試使用

For I = lastrow To 1 Step -1 
     Set mycell = ws.Cells(I, 1) 

,而不是你的每個循環。 (將下一個語句更改爲Next I)開始從底部刪除。

+0

工程就像一個魅力。太感謝了 –