2017-01-16 114 views
0

此代碼讓我們更改一個表中的值,然後在另一個範圍內尋找原始值(「oldcode」),如果有一個或多個出現'其他範圍',它用newcode替換所有舊代碼。VBA-添加字符環路.findnext不退出循環

從newcode帶走字符時這工作完全,但是,即使添加一個字符newcode時,循環永遠不會停止。例如,如果當前(oldcode)是「Test」,並且輸入「tes」,則代碼將激發,並且所有「test」都將更改爲「tes」。如果我將「測試」更改爲「測試1」,則全部更改爲「測試1」,但即使C沒有任何變化,循環仍繼續運行。如果在這樣做似乎沒有幫助。

我還要提到oldcode不是直接「測試」,Oldcode實際上來自第1列,它concats「測試」和計數有多少人在那裏,所以「測試1」。

任何幫助將不勝感激!

Private Sub worksheet_change(ByVal target As Range) 

Dim row As Integer 
Dim column As Integer 
Dim i As Integer 
Dim oldcode As String 
Dim newcode As String 
Dim IssueLogSheet As Worksheet 
Dim FailureModeTable As Range 
Dim max As Integer 


Set IssueLogSheet = Sheets("Issue Log") 
Set FailureModeTable = IssueLogSheet.Range("FMCODE") 

row = target.row 
column = target.column 



    If Not Intersect(target, FailureModeTable) Is Nothing And (target.column <> 1 Or target.column <> 4) Then 


     Application.EnableEvents = False 
     Application.Undo 
     oldcode = Cells(row, 1).Value 
     oldcode = WorksheetFunction.Proper(oldcode) 
     Application.Undo 
     Application.EnableEvents = True 
     MsgBox oldcode 


      With IssueLogSheet.Range("IssueLogFailureName") 
      Set c = .Find(oldcode, LookIn:=xlValues) 

       If Not c Is Nothing Then 
       newcode = Cells(row, 1).Value 
       newcode = WorksheetFunction.Proper(newcode) 


        Do 
         If c Is Nothing Then 
         Exit do 
         End If 
        c.Value = newcode 
        Set c = .FindNext(c) 
        Loop While Not c Is Nothing 


       End If 

      End With 

     End If 

End Sub 

回答

0

添加

Dim firstAddress As String 

和改變循環如下:

With IssueLogSheet.Range("IssueLogFailureName") 
     Set c = .Find(oldcode, LookIn:=xlValues) 

     If Not c Is Nothing Then 
      firstAddress = c.Address '<--| store first occurrence address 
      newcode = WorksheetFunction.Proper(Cells(row, 1).Value) 
      Do 
       c.Value = newcode 
       Set c = .FindNext(c) 
      Loop While Not c Is Nothing And c.Address <> firstAddress '<--| exit should 'Find()' wrap back to first occurrence 
     End If 
    End With 

否則只是改變了循環如下

With IssueLogSheet.Range("IssueLogFailureName") 
     Set c = .Find(oldcode, LookIn:=xlValues, lookat:=xlWhole) '<--| impose a full match 

     If Not c Is Nothing Then 
      newcode = WorksheetFunction.Proper(Cells(row, 1).Value) 
      Do 
       c.Value = newcode 
       Set c = .FindNext(c) 
      Loop While Not c Is Nothing 
     End If 
    End With 
+0

這定了!謝謝你的幫助! –

+0

不客氣 – user3598756