Find and Replace values not equal to

akjohno

New Member
Joined
Mar 27, 2018
Messages
27
Office Version
  1. 365
Platform
  1. Windows
Hi all, I have some code to change values of say column D in a worksheet. It looks at the values (numeric) and then if it finds say a 400 it replaces that text to "%po", and then if it finds 700 it replaces that with "". I do this using the Selection.Replace so it does it extremely quickly. I now want to be able to replace any other value in that column to the text "%sp" but i want it to do it as fast as possible. is there a way to code the Selection.Replace to do a search for does not equal? I can get the code to work by use Select Case or counter type methods, but as the sheet can have hundreds of thousands of rows I don't want the users to have the annoying flickering if it examining each row by itself and looping through if possible. Part of my code below for reference.

Columns("D:D").Select 'Select the column we want to search for feature codes
Selection.Replace What:="700", Replacement:="", LookAt:=xlWhole, _
SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:="400", Replacement:="%po", LookAt:=xlWhole, _
SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False

Regards,
Andrew
 
You may need to investigate to vba command "DoEvents"
Thanks Peter, I'll look in to that next. Can you advise whether the "Copy Destination" code from above has some way of pasting values instead of contents?
 
Upvote 0

Excel Facts

Ambidextrous Undo
Undo last command with Ctrl+Z or Alt+Backspace. If you use the Undo icon in the QAT, open the drop-down arrow to undo up to 100 steps.
If you only want values then you don't really need copy/paste at all. Try ..

VBA Code:
Sub Demo_v2()
  Dim wsNew As Worksheet
  
  Application.ScreenUpdating = False
  Set wsNew = Sheets.Add(After:=Sheets("Sheet2"))
  With Sheets("Sheet2").UsedRange
    wsNew.Range(.Address).Value = .Value
  End With
  Application.ScreenUpdating = True
End Sub
 
Upvote 0
If you only want values then you don't really need copy/paste at all. Try ..

VBA Code:
Sub Demo_v2()
  Dim wsNew As Worksheet
 
  Application.ScreenUpdating = False
  Set wsNew = Sheets.Add(After:=Sheets("Sheet2"))
  With Sheets("Sheet2").UsedRange
    wsNew.Range(.Address).Value = .Value
  End With
  Application.ScreenUpdating = True
End Sub
Thanks Peter. That has got the majority of the sheet working well now. The only one left (fingers crossed) is to do that between worksheets. So i have a named range I want to copy from one worksheet to the next worksheet and put those values in the named range. Would the coding be similar as right now it is bombing my whole sheet out for some reason....
 
Upvote 0
Thanks Peter. That has got the majority of the sheet working well now. The only one left (fingers crossed) is to do that between worksheets. So i have a named range I want to copy from one worksheet to the next worksheet and put those values in the named range. Would the coding be similar as right now it is bombing my whole sheet out for some reason....
Think I have it...
VBA Code:
    With Sheets("Sheet1").Range(coords)
        Worksheets(wsname).Range(pastearea2).Value = .Value
    End With
 
Upvote 0
If you only want values then you don't really need copy/paste at all. Try ..

VBA Code:
Sub Demo_v2()
  Dim wsNew As Worksheet
 
  Application.ScreenUpdating = False
  Set wsNew = Sheets.Add(After:=Sheets("Sheet2"))
  With Sheets("Sheet2").UsedRange
    wsNew.Range(.Address).Value = .Value
  End With
  Application.ScreenUpdating = True
End Sub
Ok so code completed and I "thought" it was working. Something happening inside the code somewhere and sometimes. I can run the code on my machine with no issues, someone else tries it and it gives goobledy gook....That aside, now I have just tried running a larger number of data inputs and the code seems to run completely fine but the data doesn't copy properly. When I go and try to F8 (Step Into) in the code sometimes it just automatically runs and won't let me step through, other times it gives me an error that says "Copy Method of Range Class Failed" Code as per below. It appears to be unhappy with my copying cell ranges for some reason???? So far I have changed my variable Numshots from Integer to Long and Pastevalue from String to Variant.Have I declared a variable incorrectly? Any ideas?

VBA Code:
Sub Convert()

' Conversion Macro

'On Error GoTo errorhandler
'Variable Declarations
    Dim NumShots As Long
    Dim wbname As String, wsname As String, fullpath As String, sp As String, coords2 As String
    Dim name1 As String, name2 As String, pastearea2 As String, coords As String
    Dim wsnew As Worksheet
    Dim a As Variant, pastearea As Variant
    Dim i As Long
    'Stop screen from flickering while windows change
    Application.ScreenUpdating = False
    
    '   Asks you where the file you want to convert is located
    With Application.FileDialog(msoFileDialogFilePicker)    'Start of picking your file
            .AllowMultiSelect = False               'Allows you to only open one file
            .Filters.Add "Text Files", "*.dat", 1   'Looks only for .dat files
            .Show                                   'Opens the File Dialog Box
        fullpath = .SelectedItems.Item(1)           'Assigns the location of the file to the variable "fullpath"
    End With                                        'Exits the search function
    
    If Right(fullpath, 3) <> "dat" Then             'Error trap in case you don't select a dat file
        MsgBox ("You need to select a .dat file!")  'Message box to advise user that a dat file wasn't selected
        'GoTo errorhandler                           'Sends you to the error trap which will close code down
    End If                                          'End of picking your file
    
    'Assigning variable fullpath to full address of file and imports file data into the dat file correctly delimited
    Workbooks.OpenText Filename:= _
        fullpath, _
        Origin:=xlMSDOS, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
        xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=False, Semicolon:=False, _
        Comma:=False, Space:=True, Other:=False, FieldInfo:=Array(Array(1, 1), _
        Array(2, 1), Array(3, 1), Array(4, 1)), TrailingMinusNumbers:=True
    
    wbname = ActiveWorkbook.Name                    'Assigns variable wbname to the name of this workbook
    wsname = ActiveSheet.Name                       'Assigns variable wsname the name of this worksheet
    NumShots = Application.WorksheetFunction.CountA(Range("A:A"))   'Counts the number of survey points in the file
    Set wsnew = Sheets.Add(After:=Sheets(wsname))   'Adds a new worksheet
    
    'Copies the co-ordinate converter section of the main file to this dat file
    Windows("CATAN Converter.xlsm").Activate        'Activates main workbook
    Sheets("Sheet2").UsedRange.Copy Destination:=Workbooks(wbname).Worksheets("Sheet1").Range("A1")  'Copies conversion data over
    Windows(wbname).Activate                        'Goes back and selects our new dat workbook
        
    pastearea = "G5:AF" & NumShots + 3              'Assigns the variable pastearea the value of the cells we need to paste to
    Range("G4:AF4").Copy Destination:=ActiveSheet.Range(pastearea)  'Copies the formulas from cells G4 to AF4
    ActiveWorkbook.Worksheets(1).Activate           'Selects the first worksheet in the workbook
    pastearea2 = "A1:B" & NumShots                  'Assigns the variable pastearea2 the value of all the cells we need to copy
    'Sheets("Sheet1").Range("D4:E" & NumShots + 3).Value = Range(pastearea2).Value 'Copies co-ordinates to conversion sheet
    Sheets(wsname).Range(pastearea2).Copy Destination:=ThisWorkbook.Worksheets("Sheet1").Range("D4")
    Sheets("Sheet1").Select            'Selects our co-ordinate transformation sheet1
    Range("A1").Select                              'Selects cell A1 to prevent any confusion
    
    'Copy converted co-ordinates back to final sheet
    coords = "AD4:AE" & NumShots + 3                'Assigns the variable coords the value of all the converted co-ordinate cells we need to copy
    Sheets("Sheet1").Range(coords).Copy             'Selects converted coordinates to transfer back to main sheet
    Worksheets(wsname).Range(pastearea2).PasteSpecial Paste:=xlPasteValues, operation:=xlNone, skipblanks:=False, Transpose:=False  'Pastes to main sheet
    Application.CutCopyMode = False                 'Turns off the clipboard selection
    Range("A1").Select                              'Selects cell A1 to prevent any confusion
    Sheets("Sheet1").Select                         'Selects Sheet1
    Application.DisplayAlerts = False               'Turns off Display of box asking to accept sheet deletion
    ActiveWindow.SelectedSheets.Delete              'Deletes Sheet1
    Application.DisplayAlerts = True                'Turns display alerts back on
   
  ' Converts Feature Codes to CATAN usable format
    With Range("D1", Range("D" & Rows.Count).End(xlUp))
        a = .Value
        For i = 1 To UBound(a)
            Select Case a(i, 1)
                Case 700: a(i, 1) = vbNullString
                Case 400: a(i, 1) = "%po"
                Case Else: a(i, 1) = "%sp"
            End Select
        Next i
        .Value = a
    End With
    
    'Saving of new file for CATAN
    name1 = InStrRev(fullpath, ".")                 'Counts the number of characters in front of the . in the file name
    name2 = Left(fullpath, name1)                   'Grabs the name of the file using the character count above
    'Uses the filename from above and puts csv after it so that it saves to the same location as a different file type
    ActiveWorkbook.SaveAs Filename:= _
    name2 & "csv", FileFormat:=xlCSV, CreateBackup:=False
    MsgBox "Created " & name2 & "csv for use in CATAN." & vbNewLine & "File location same as original file location"  'Advises user the file location
    ActiveWorkbook.Close                            'Closes this file
    Workbooks("CATAN Converter.xlsm").Close savechanges:=False  'Closes the Master workbook
Exit Sub
'errorhandler:
    'MsgBox "An Error has occurred." & vbNewLine & "Please re-run."
    'Exit Sub
End Sub
 
Upvote 0
sorry it should be the variable pastearea not pastevalue in the comment I wrote.
 
Upvote 0
ok so i have changed my variables and code a little, and now instead of it stopping its copy/paste at cells around row 5000/6000 it copies all the way up until cell 29000ish this time but still won't copy the rest... Errors seem to be happening in this area of code.

VBA Code:
 pastearea = "G5:AF" & NumShots + 3              'Assigns the variable pastearea the value of the cells we need to paste to
    Range("G4:AF4").Copy Destination:=ActiveSheet.Range(pastearea)  'Copies the formulas from cells G4 to AF4
    ActiveWorkbook.Worksheets(1).Activate           'Selects the first worksheet in the workbook
    pastearea2 = "A1:B" & NumShots                  'Assigns the variable pastearea2 the value of all the cells we need to copy
    'Sheets("Sheet1").Range("D4:E" & NumShots + 3).Value = Range(pastearea2).Value 'Copies co-ordinates to conversion sheet
    Sheets(wsname).Range(pastearea2).Copy Destination:=Worksheets("Sheet1").Range("D4")
    Sheets("Sheet1").Select                         'Selects our co-ordinate transformation sheet1
    Range("A1").Select                              'Selects cell A1 to prevent any confusion

Full new code is as follows:


VBA Code:
Sub Convert()

'Conversion Macro

On Error GoTo errorhandler
'Variable Declarations
    Dim NumShots As Long
    Dim wbname As String, wsname As String, fullpath As String, sp As String, coords2 As String
    Dim name1 As String, name2 As String, pastearea As String, pastearea2 As String, coords As String
    Dim wsnew As Worksheet
    Dim a As Variant
    Dim i As Long
    'Stop screen from flickering while windows change
    Application.ScreenUpdating = False
    
    '   Asks you where the file you want to convert is located
    With Application.FileDialog(msoFileDialogFilePicker)    'Start of picking your file
            .AllowMultiSelect = False               'Allows you to only open one file
            .Filters.Add "Text Files", "*.dat", 1   'Looks only for .dat files
            .Show                                   'Opens the File Dialog Box
        fullpath = .SelectedItems.Item(1)           'Assigns the location of the file to the variable "fullpath"
    End With                                        'Exits the search function
    
    If Right(fullpath, 3) <> "dat" Then             'Error trap in case you don't select a dat file
        MsgBox ("You need to select a .dat file!")  'Message box to advise user that a dat file wasn't selected
        GoTo errorhandler                           'Sends you to the error trap which will close code down
    End If                                          'End of picking your file
    
    'Assigning variable fullpath to full address of file and imports file data into the dat file correctly delimited
    Workbooks.OpenText Filename:= _
        fullpath, _
        Origin:=xlMSDOS, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
        xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=False, Semicolon:=False, _
        Comma:=False, Space:=True, Other:=False, FieldInfo:=Array(Array(1, 1), _
        Array(2, 1), Array(3, 1), Array(4, 1)), TrailingMinusNumbers:=True
    
    wbname = ActiveWorkbook.Name                    'Assigns variable wbname to the name of this workbook
    wsname = ActiveSheet.Name                       'Assigns variable wsname the name of this worksheet
    NumShots = Application.WorksheetFunction.CountA(Range("A:A"))   'Counts the number of survey points in the file
    Set wsnew = Sheets.Add(After:=Sheets(wsname))   'Adds a new worksheet
    
    'Copies the co-ordinate converter section of the main file to this dat file
    Windows("CATAN Converter.xlsm").Activate        'Activates main workbook
    Sheets("Sheet2").UsedRange.Copy Destination:=Workbooks(wbname).Worksheets("Sheet1").Range("A1")  'Copies conversion data over
    Windows(wbname).Activate                        'Goes back and selects our new dat workbook
        
    pastearea = "G5:AF" & NumShots + 3              'Assigns the variable pastearea the value of the cells we need to paste to
    Range("G4:AF4").Copy Destination:=ActiveSheet.Range(pastearea)  'Copies the formulas from cells G4 to AF4
    ActiveWorkbook.Worksheets(1).Activate           'Selects the first worksheet in the workbook
    pastearea2 = "A1:B" & NumShots                  'Assigns the variable pastearea2 the value of all the cells we need to copy
    'Sheets("Sheet1").Range("D4:E" & NumShots + 3).Value = Range(pastearea2).Value 'Copies co-ordinates to conversion sheet
    Sheets(wsname).Range(pastearea2).Copy Destination:=Worksheets("Sheet1").Range("D4")
    Sheets("Sheet1").Select                         'Selects our co-ordinate transformation sheet1
    Range("A1").Select                              'Selects cell A1 to prevent any confusion
    
    'Copy converted co-ordinates back to final sheet
    coords = "AD4:AE" & NumShots + 3                'Assigns the variable coords the value of all the converted co-ordinate cells we need to copy
    With Sheets("Sheet1").Range(coords)
        Worksheets(wsname).Range(pastearea2).Value = .Value
    End With
    
    Range("A1").Select                              'Selects cell A1 to prevent any confusion
    Sheets("Sheet1").Select                         'Selects Sheet1
    Application.DisplayAlerts = False               'Turns off Display of box asking to accept sheet deletion
    ActiveWindow.SelectedSheets.Delete              'Deletes Sheet1
    Application.DisplayAlerts = True                'Turns display alerts back on
   
  ' Converts Feature Codes to CATAN usable format
    With Range("D1", Range("D" & Rows.Count).End(xlUp))
        a = .Value
        For i = 1 To UBound(a)
            Select Case a(i, 1)
                Case 700: a(i, 1) = vbNullString
                Case 400: a(i, 1) = "%po"
                Case Else: a(i, 1) = "%sp"
            End Select
        Next i
        .Value = a
    End With
    
    'Saving of new file for CATAN
    name1 = InStrRev(fullpath, ".")                 'Counts the number of characters in front of the . in the file name
    name2 = Left(fullpath, name1)                   'Grabs the name of the file using the character count above
    'Uses the filename from above and puts csv after it so that it saves to the same location as a different file type
    ActiveWorkbook.SaveAs Filename:= _
    name2 & "csv", FileFormat:=xlCSV, CreateBackup:=False
    MsgBox "Created " & name2 & "csv for use in CATAN." & vbNewLine & "File location same as original file location"  'Advises user the file location
    ActiveWorkbook.Close                            'Closes this file
    Workbooks("CATAN Converter.xlsm").Close savechanges:=False  'Closes the Master workbook
Exit Sub
errorhandler:
    MsgBox "An Error has occurred." & vbNewLine & "Please re-run."
    Exit Sub
End Sub
 
Upvote 0
I'm afraid I cannot easily identify what would be causing the varying behaviour, sorry. Obviously I do not have (& don't want) the huge files that you are working with either.
 
Upvote 0
I'm afraid I cannot easily identify what would be causing the varying behaviour, sorry. Obviously I do not have (& don't want) the huge files that you are working with either.
No worries Peter. Any ideas why the VBA Editor isn’t letting me Step Into to try and error hunt? The files are just text files, luckily....Only about 2-3MB at most.
 
Upvote 0

Forum statistics

Threads
1,214,986
Messages
6,122,611
Members
449,090
Latest member
vivek chauhan

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top