2015-04-12 161 views
1

我對這個論壇和Excel VBA很新。我有一段時間通過玩VBA學到了一些東西。但現在我陷入了這個小問題,我相信Excel Guru在這裏可以幫助我。任何幫助,將非常感激。下面是我的問題多個條件查找並替換

摘要:

我在列A:F 我想找到和C列具有取決於價值C柱和柱A十六進制值替換其值的電子表格。

例子:

如果列A = 1和列C = General然後用0x0001

但如果更換GeneralA = 2和列C = General然後用0x0002

我的代碼替換General

Columns("C").Replace What:=" General", Replacement:=" 0x0001", LookAt:=xlWhole, _SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ReplaceFormat:=False

問題:

我目前擁有的代碼只着眼於C列中的值,從而改變每次General0x0001

回答

1

如果你開始:

enter image description here

運行此宏:

Sub Changes() 
    Dim N As Long, i As Long 
    N = Cells(Rows.Count, 1).End(xlUp).Row 
    For i = 1 To N 
     v1 = Cells(i, 1).Value 
     v3 = Cells(i, 3).Value 
     If v1 = 1 And v3 = "General" Then Cells(i, 3).Value = "0x0001" 
     If v1 = 2 And v3 = "General" Then Cells(i, 3).Value = "0x0002" 
    Next i 
End Sub 

會產生:

enter image description here

1

除了@ garys-學生回答,我想說的是「案例」方法,更容易爲大決策樹,如:

Sub Changes() 
    Dim N As Long, i As Long 
    N = Cells(Rows.Count, 1).End(xlUp).Row 
    For i = 1 To N 
     v1 = Cells(i, 1).Value 
     v3 = Cells(i, 3).Value 
     Select Case v1 
      Case 1 
       Select Case v3 
        Case "General" 
         Cells(i, 3).Value = "0x0001" 
        Case Else 
       End Select 
      Case 2 
       Select Case v3 
        Case "General" 
         Cells(i, 3).Value = "0x0002" 
        Case Else 
       End Select 
      Case Else 
     End Select 
    Next i 
End Sub 

「選擇案例V1」去代替「如果V1 =」,然後在「案例1」完成它「如果V1 = 1" 。

1

我會使用If和Case的組合,V3測試只有一個可能的觸發器,不需要大小寫。

Sub Changes() 
    Dim N As Long, i As Long 
    N = Cells(Rows.Count, 1).End(xlUp).Row 
    For i = 1 To N 
     v1 = Cells(i, 1).Value 
     v3 = Cells(i, 3).Value 
     If v3 = "General" Then 
      Select Case v1 
       Case 1 
        Cells(i, 3).Value = "0x0001" 
       Case 2 
        Cells(i, 3).Value = "0x0002" 
       Case Else 
      End Select 
     End If 
    Next i 
End Sub