2014-11-07 5 views
1

이 포함 된 Excel 워크 시트의 특정 행 식별 다양한 데이터 원본에서 가져온 여러 워크 시트가 포함 된 Excel 파일을 얻을 수 있습니다. 일부 워크 시트에는 끝 부분에 표준화 된 고지 사항이 삽입되어 있지만 일부는 그렇지 않습니다. 그러나 면책 조항이 나타나면 항상 같은 텍스트로 시작하고 항상 같은 열에 나타납니다. 전체 Excel 파일을 검색 할 VBA 스크립트를 작성하려고합니다. 면책 조항이 존재하는지 확인하고, 그렇다면 그들이 시작하는 행을 결정합니다. 그 행에서 마지막으로 사용 된 행까지 모든 셀을 지우십시오.VBA를 사용하여 텍스트의 하위 문자열

StackOverflow 및 기타 리소스를 통해 사냥을 통해 알 수있는 한, 아래 코드가 작동해야합니다. 그러나 어떤 이유에서인지, 키 하위 문자열이있는 시점 (실제로있을 때조차도)을 실제로 식별하지 않습니다. 누군가 내가 잘못 가고있는 것을 지적 할 수 있습니까?

Option Explicit 

Option Base 1 

Sub Delete_Disclaimers() 

' Turn off screen updating for speed 

Application.ScreenUpdating = False 


' Define variables 

Dim ws As Worksheet 
Dim TextCheck As String 
Dim StartRow As Integer 
Dim EndRow As Integer 
Dim SearchColumn As Integer 
Dim CheckVal As Integer 
Dim CurrentCell As Range 
Dim RowCount As Integer 
Dim SearchText As String 


' Cycle through each worksheet in the workbook 
For Each ws In ActiveWorkbook.Worksheets 


'Set some initial variables for this worksheet 

SearchColumn = 2 
StartRow = 1 
SearchText = "Disclaimer" 

' Set EndRow to the last row used in the worksheet 
EndRow = CInt(ws.UsedRange.SpecialCells(xlCellTypeLastCell).Row) 


' Find the cell, if any, that has the text by searching just in column B to speed things up. Also limit to the first 200 rows 
' for speed since there don't seem to have any sheets longer than that.  

For RowCount = 1 To 200 
    Set CurrentCell = ws.Cells(2, RowCount) 
    TextCheck = CurrentCell.Text 
    If Not TextCheck = "" Then 
     CheckVal = InStr(1, TextCheck, SearchText, 1) 
     If CheckVal > 0 Then 
      StartRow = RowCount 
      MsgBox ("Start Row is " & CStr(StartRow)) 
      Exit For 
     End If 
    End If 
Next RowCount 


' If the search text was found, clear the range from the start row to the end row. 

If StartRow > 1 Then 
    ws.Range(ws.Cells(1, StartRow), ws.Cells(50, EndRow)).Clear 
End If 



' Loops to next Worksheet 
Next ws 


' Turn screen updating back on 
Application.ScreenUpdating = True 


' Display a message box that all sheets have been cleared, now that screenupdating is back on 
MsgBox "All Worksheets have been cleared!" 


End Sub 
+1

[이] (http://www.siddharthrout.com/2011/07/14/find-and-findnext-in-excel-vba/) 올바른 궤도 –

+0

Siddarth에서 당신을 얻을 것이다, 감사 링크를 위해. 나는 시도했다. 이것을 게시하기 전에 찾아 보아라. 예제로 돌아가서 수정을 한 후에도, 나는 여전히 일치하는 것을 찾지 못했다. 다음은 스 니펫입니다. ws.Range ("b1 : b200") Set CurrentCell = ws.Cells.Find (What : = SearchText, LookIn : = xlValues, LookAt : = xlPart, SearchOrder : = xlByRows, SearchDirection : = xlNext , MatchCase : = False, SearchFormat : = False) 현재 셀이 아닌 경우 StartRow = CInt (CurrentCell.Row) 끝 부분 – Vaasa

답변

1

셀 구문이 잘못되었습니다. 셀 (행, 열)이어야합니다. 행과 열이 바뀌 었습니다.

+0

고마워요! 이것은 확실히 도움이되었습니다. – Vaasa

1

내 솔루션은 위의 두 가지 답변의 조합이되었습니다. 그러나 .Clear 섹션은 제가 간과했던 주요한 정의입니다. 비슷한 문제가있는 다른 사람들을 돕기 위해 전체 업데이트 코드가 있습니다.

Option Explicit 

Option Base 1 

Sub Delete_Portfolio_Holdings() 

' Turn off screen updating for speed 

Application.ScreenUpdating = False 


' Define variables 

Dim ws As Worksheet 
Dim TextCheck As String 
Dim StartRow As Integer 
Dim EndRow As Integer 
Dim SearchColumn As Integer 
Dim CheckVal As Integer 
Dim CurrentCell As Range 
Dim RowCount As Integer 
Dim SearchText As String 
Dim ClearRange As Range 

Dim WScount As Integer 
Dim cws As Integer 


' Cycle through each worksheet in the workbook 

WScount = ActiveWorkbook.Worksheets.Count 

For cws = 1 To WScount 


'Set some initial variables for this worksheet 

SearchColumn = 2 
StartRow = 1 
SearchText = "Disclaimer" 
Set ws = ActiveWorkbook.Worksheets(cws) 

' Set EndRow to the last row used in the worksheet 
EndRow = CInt(ws.UsedRange.SpecialCells(xlCellTypeLastCell).Row) 


' Find the cell, if any, that has the text by searching just in column B to speed things up. Also limit to the first 200 rows 
' for speed since you don't seem to have any sheets longer than that. You can always change to increase if necessary. Cells.Find 
' does not return anything if there is no match for the text, so CurrentRow may not change. 

With ws.Range("b1:b200") 
    Set CurrentCell = ws.Cells.Find(What:=SearchText, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False) 
    If Not CurrentCell Is Nothing Then 
     StartRow = CInt(CurrentCell.Row) 
    End If 
End With 


' Now if the text was found we now have identified the start and end rows of the caveats, we can clear columns A through BB with the .Clear function. Choice of column BB is arbitary. 

If StartRow > 1 Then 
    Set ClearRange = ws.Range(("A" & StartRow), ("BB" & EndRow)) 
    MsgBox ("ClearRange is " & CStr(ClearRange.Address)) 
    ClearRange.Clear 
End If 



' Loops to next Worksheet 
Next cws 


' Turn screen updating back on 
Application.ScreenUpdating = True 


' Display a message box that all sheets have been cleared, now that screenupdating is back on 
MsgBox "All Worksheets have been cleared!" 


End Sub 
+0

코드 블록의 올바른 언어 코드는 http://stackoverflow.com/editing-help#syntax-highlighting에서 볼 수 있듯이'vb'이거나 아무것도 아닌'lang-html'이 아니며' 스 니펫 (swippet) '태그는 브라우저에서 실제로 실행 가능하지 않습니다. 당신이/수정할 수있는 [편집] (http://stackoverflow.com/posts/26812073/edit) 버튼을 사용하여 – xmojmr

+0

당신이 관심이 있다면 당신의 경우에'.Find'를 사용하는 방법에 대한 해결책을 게시 할 수 있습니다. .. –

+0

나는 대답을 찾았다. 대체 방법이있는 경우 언제든지 추가하십시오. 하나는 대체 옵션에 대해 배우는 것에 관심이 있습니다. – Vaasa

관련 문제