简体   繁体   中英

VBA - Replace with find one word in a specific cell works, how do I find one word or another?

First I should apologize for my very limited VBA coding skills. So the code I have basically does what I want it to do: I have hundreds of Excel files I need to modify at a time repeatedly. If a specific cell ("B1") has the word string "draw" in it, nothing is to happen. If the cell doesn't have the word string "draw", the word "tank" is to be inserted before the word "prep" in the cell. The macro runs through all the files in a given folder, changes the format, outputs to a new folder, etc. This all works beautifully. But on occasion, the cell may contain the word string "pool" instead of "draw". In that case, I don't want to change the cell contents at all. So basically, if "pool" or "draw" is in the cell, do nothing. If they're both not present, add "Tank" before the word string "prep" in the cell. Here's the code I have:

Sub SIS_ALIMS()

Dim wbOpen As Workbook
Dim MyDir As String
MyDir = "C:\Processed data"
strExtension = Dir(MyDir & "\*.xls")
While strExtension <> vbNullString
Set wbOpen = Workbooks.Open(MyDir & "\" & strExtension)
With wbOpen

Set rgFound = Range("B1").Find("draw", MatchCase:=False)

If rgFound Is Nothing Then

Range("B1").replace What:="prep", Replacement:="Tank prep"

Else

End If

Dim SaveName As String
    SaveName = ActiveSheet.Range("B8").Text
    ActiveWorkbook.SaveAs fileName:="C:\Processed data\ALIMS data\" & _
    SaveName & ".txt"

.Close SaveChanges:=False

End With
strExtension = Dir
Wend

Application.ScreenUpdating = True

End Sub

First an observation: Your code does not specify a worksheet in wbOpen , so you may run into problems if a workbook happens not to open on the worksheet you expect. Better to use something like With wbOpen.Sheets(1) .

As for your question, instead of using Find you may find it easier to work with the cell value as a string variable:

Dim CellData As String
    
With wbOpen.Sheets(1)
    CellData = .Range("B1").Value
        
    If CellData = "draw" Or CellData = "pool" Then
        'do nothing
            
    ElseIf CellData = "prep" Then
        .Range("B1").Value = "Tank prep"
            
    Else
        'add other conditionals as needed
            
    End If
        
End With

Finally, if the VBA doesn't need to perform any action when the cell value is "draw" or "pool," then testing for those values is superfluous. The If... End If block can be replaced with just the conditional that is of interest:

If .Range("B1").Value = "prep" Then .Range("B1").Value = "Tank prep"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM