2012-06-05 2 views
4

나는 하루 동안 이걸로 화를 냈고, 높거나 낮게 검색했고, 아마도 너무 귀여워 져서 완전히 붙어 있습니다. 하지 다른 경우 VBA를 사용하여 셀 내에서 문자열 찾기

나는 셀이 포함되어있는 경우 다음

는 "%는"나는 한 일을하려는 경우 간단한을 실행하려고하고 있어요. 나는 그것을 이해할 수없는 이유로 그것을 해결할 수 없습니다. 나는 분명히 다른 곳에서 몇 가지 아이디어를 얻었지만 여전히 작동시킬 수는 없다.

복잡한 요소 - 전체 열, 단지 테이블에서이를 실행하지 않으므로 로트 또는 상대 ActiveCell을 사용하는 더 큰 하위에 포함됩니다. Range가 항상 가변적이어야하므로 A 열에서 "% Change"를 실행할 곳을 알 수 없습니다. VBA/VBE가 "%"가 포함 된 셀에 대해 다른 작업을 수행하기를 원합니다. SO

다음

는 원시 데이터가

Initial Value (6/30/06) 

Value (12/31/06) 

Net Additions (9/30/07) 

Withdrawal (12/07) 

Value (12/31/07) 

Withdrawal (2008) 

Value (12/31/08) 

Addition (8/26/09) 

Value (12/31/09) 

Value (12/31/10) 

Value (12/30/11) 

Value (3/31/12) 

% Change 1st Quarter 

% Change Since Inception 

처럼 보인다하지만 실행할 때 "그것이 반대로 그것이"그럼이 "로 꺼내해야 나쁜 루프에 걸리면 다음과 같은 것입니다 Else "하위의 일부.

Sub IfTest() 
'This should split the information in a table up into cells 
Dim Splitter() As String 
Dim LenValue As Integer  'Gives the number of characters in date string 
Dim LeftValue As Integer 'One less than the LenValue to drop the ")" 
Dim rng As Range, cell As Range 
Set rng = ActiveCell 

Do While ActiveCell.Value <> Empty 
    If InStr(rng, "%") = True Then 
     ActiveCell.Offset(0, 0).Select 
     Splitter = Split(ActiveCell.Value, "% Change") 
     ActiveCell.Offset(0, 10).Select 
     ActiveCell.Value = Splitter(1) 
     ActiveCell.Offset(0, -1).Select 
     ActiveCell.Value = "% Change" 
     ActiveCell.Offset(1, -9).Select 
    Else 
     ActiveCell.Offset(0, 0).Select 
     Splitter = Split(ActiveCell.Value, "(") 
     ActiveCell.Offset(0, 9).Select 
     ActiveCell.Value = Splitter(0) 
     ActiveCell.Offset(0, 1).Select 
     LenValue = Len(Splitter(1)) 
     LeftValue = LenValue - 1 
     ActiveCell.Value = Left(Splitter(1), LeftValue) 
     ActiveCell.Offset(1, -10).Select 
    End If 
Loop 
End Sub 

감사합니다.

답변

3

나는 셀에있는 "%"에 대한 테스트를 분리하는 코드를 단순화. 일단 작동하게되면 나머지 코드를 추가 할 수 있습니다.

이 시도 :

Option Explicit 


Sub DoIHavePercentSymbol() 
    Dim rng As Range 

    Set rng = ActiveCell 

    Do While rng.Value <> Empty 
     If InStr(rng.Value, "%") = 0 Then 
      MsgBox "I know nothing about percentages!" 
      Set rng = rng.Offset(1) 
      rng.Select 
     Else 
      MsgBox "I contain a % symbol!" 
      Set rng = rng.Offset(1) 
      rng.Select 
     End If 
    Loop 

End Sub 

InStr가 검색 텍스트 문자열에 나타나는 횟수를 반환합니다. if 테스트를 변경하여 먼저 일치하는 항목이 없는지 확인하십시오.

메시지 상자와 .Selects은 코드를 단계별로 실행하는 동안 어떤 일이 일어나고 있는지 간단히 볼 수 있습니다. 일단 작동 시키면 가져 가라.

+0

이것은 내가 놓친 퍼즐의 간단한 조각입니다. 나는 여전히 상대적으로 새로운 오전 그래서 if (if 아마도 알 수없는 :) if 함수 내에서 rng.offset을 설정할 수있는 능력에 대해 생각하지 않았다. 그것은 위대하고 매우 도움이됩니다. 또한 InStr 함수에 대해 = 0과 반대되는 참 거짓을 사용하고있었습니다. 아직 완전히 얻지는 못했지만 감사합니다. 너무 감사합니다! –

+0

좋은 거래 - 다행 지금 당신을 위해 일하고있다. 3 가지 유용한 답변이있는 것 같습니다. 가장 도움이되는 질문 옆에있는 체크 표시를 클릭하여 "대답"으로 받아들입니다. 그리고 stackoverflow에 오신 것을 환영합니다. –

+0

+1 멋지게 완료했습니다. –

0

당신이 rng의 값을 변경하지 않을 그래서 항상
True은 초기 셀에 루프

또한

전에 새로운 라인에 Set rng = rng.Offset(1, 0), 당신의 InStr 테스트는 항상 실패합니다

사본 포인트 -1 문자열이 발견되면 InStr에서 반환 값은 0보다 커집니다. = 사실

새로운 코드를 제거하기 위해 테스트를 변경합니다

Sub IfTest() 
'This should split the information in a table up into cells 
Dim Splitter() As String 
Dim LenValue As Integer  'Gives the number of characters in date string 
Dim LeftValue As Integer 'One less than the LenValue to drop the ")" 
Dim rng As Range, cell As Range 
Set rng = ActiveCell 

Do While ActiveCell.Value <> Empty 
    If InStr(rng, "%") Then 
     ActiveCell.Offset(0, 0).Select 
     Splitter = Split(ActiveCell.Value, "% Change") 
     ActiveCell.Offset(0, 10).Select 
     ActiveCell.Value = Splitter(1) 
     ActiveCell.Offset(0, -1).Select 
     ActiveCell.Value = "% Change" 
     ActiveCell.Offset(1, -9).Select 
    Else 
     ActiveCell.Offset(0, 0).Select 
     Splitter = Split(ActiveCell.Value, "(") 
     ActiveCell.Offset(0, 9).Select 
     ActiveCell.Value = Splitter(0) 
     ActiveCell.Offset(0, 1).Select 
     LenValue = Len(Splitter(1)) 
     LeftValue = LenValue - 1 
     ActiveCell.Value = Left(Splitter(1), LeftValue) 
     ActiveCell.Offset(1, -10).Select 
    End If 
Set rng = rng.Offset(1, 0) 
Loop 

End Sub 
+0

매우 좋은, inStr 테스트에 대한 설명에 감사드립니다! 그것은 매우 도움이됩니다! –

0

검색 루틴의 경우 Find, AutoFilter 또는 변형 배열 방식을 사용해야합니다.범위 루프가 아래 코드는 사용자가 선택한 범위에서 strText 변수를 찾습니다 Select

를 사용하는 경우 더 악화 다시 nomally, 너무 느린, 그것은 다음 다음 더

을 처리 할 수있는 범위 변수 rng2 모든 일치를 추가
Option Explicit 

Const strText As String = "%" 

Sub ColSearch_DelRows() 
    Dim rng1 As Range 
    Dim rng2 As Range 
    Dim rng3 As Range 
    Dim cel1 As Range 
    Dim cel2 As Range 
    Dim strFirstAddress As String 
    Dim lAppCalc As Long 


    'Get working range from user 
    On Error Resume Next 
    Set rng1 = Application.InputBox("Please select range to search for " & strText, "User range selection", Selection.Address(0, 0), , , , , 8) 
    On Error GoTo 0 
    If rng1 Is Nothing Then Exit Sub 

    With Application 
     lAppCalc = .Calculation 
     .ScreenUpdating = False 
     .Calculation = xlCalculationManual 
    End With 

    Set cel1 = rng1.Find(strText, , xlValues, xlPart, xlByRows, , False) 

    'A range variable - rng2 - is used to store the range of cells that contain the string being searched for 
    If Not cel1 Is Nothing Then 
     Set rng2 = cel1 
     strFirstAddress = cel1.Address 
     Do 
      Set cel1 = rng1.FindNext(cel1) 
      Set rng2 = Union(rng2, cel1) 
     Loop While strFirstAddress <> cel1.Address 
    End If 

    If Not rng2 Is Nothing Then 
     For Each cel2 In rng2 
      Debug.Print cel2.Address & " contained " & strText 
     Next 
    Else 
     MsgBox "No " & strText 
    End If 

    With Application 
     .ScreenUpdating = True 
     .Calculation = lAppCalc 
    End With 

End Sub 
+0

앞으로 나에게 매우 도움이 될 것입니다. 감사합니다! –

관련 문제