Replace Values in Range - excel

I've tried to do this replacement in two different ways (first attempt commented below), but it ends up replacing everything on the sheet, instead:
Sub NoNullSaveCSV()
Dim WB As Workbook
Dim WS As Worksheet
Dim find1 As Variant
Dim rplc1 As Variant
Dim find2 As Variant
Dim rplc2 As Variant
Dim Rng As Range
Application.Workbooks.Add xlWBATWorksheet
Set WB = ActiveWorkbook
Set WS = ActiveSheet
With ThisWorkbook.Worksheets("PedidosTratados")
.Range("A3:DW1000").Copy
WS.Range("A1").PasteSpecial xlPasteValues
End With
WS.Range("A1").Value = "FilterCol"
WS.Columns.AutoFilter Field:=1, Criteria1:=""
WS.UsedRange.SpecialCells(xlCellTypeVisible).EntireRow.Delete
WS.AutoFilterMode = False
ReplaceCount = ReplaceCount + Application.WorksheetFunction.CountIf(WS.Cells, "*" & fnd1 & "*")
'+ Application.WorksheetFunction.CountIf(WS.Cells, "*" & fnd2 & "*")
fnd1 = "7.9000"
rplc1 = "7.900"
fnd2 = "9.9000"
rplc2 = "9.900"
With WS
.Range("AT2:DW1000").Replace fnd1, rplc1
.Range("AT2:DW1000").Replace fnd2, rplc2
'.Cells.Replace what:=fnd1, Replacement:=rplc1, _
'LookAt:=xlPart, SearchOrder:=xlByColumns, MatchCase:=False, _
'SearchFormat:=False, ReplaceFormat:=False
'.Cells.Replace what:=fnd2, Replacement:=rplc2, _
'LookAt:=xlPart, SearchOrder:=xlByColumns, MatchCase:=False, _
'SearchFormat:=False, ReplaceFormat:=False
End With
WB.SaveAs fileName:=ThisWorkbook.Path & "\Pedidos.csv", FileFormat:=xlCSV
WB.Close False
MsgBox "Após a pesquisa, foram feitas " & ReplaceCount & " substituições."
End Sub
Could you anyone tell me why this is not restraining replacement to the specified range?
Thank you!

Related

How to export multiple sheets and save them in new created folder with same title as workbook

Tried to export worksheets to pdf with loop and save them in a newly created folder, the folder has the same name as the active workbook. Code worked in the previous file but now it won't loop anymore or save in the new folder. It creates the folder and it exports the active sheet to pdf nothing else.
When I run it I get runtime error 5 but only when I let it run as loop
I have already tried different filenames (active workbook.path & "\" &) and different ways to create a new folder (MkDir)
Sub ExportAsPDFAndSaveInNewFolder()
Dim wbA As Workbook
Dim wsA As Worksheet
Dim tdate As String
Dim fso As Object
Dim fldrName As String
Dim fldrpath As String
Dim myFile As String
Dim CF As Long, CV As Long, RF As Long, RV As Long
Dim Col As Long, Rw As Long
Dim path As String
Dim response As VbMsgBoxResult
' Set WS_Count equal to the number of worksheets in the active workbook.
Set wbA = ActiveWorkbook
Set wsA = ActiveSheet
tdate = "Dec"
'create new folder
Set fso = CreateObject("scripting.filesystemobject")
fldrName = wbA.name
fldrpath = ActiveWorkbook.path & "\" & Left(wbA.name, InStr(wbA.name, "."))
If Not fso.folderexists(fldrpath) Then
fso.createfolder (fldrpath)
End If
' Begin the loop.
For Each wsA In wbA.Sheets
wsA.Activate
'create a default name for saving file
myFile = "R Ch - S " & Year(Date) & " YTD " & tdate & " " & ActiveSheet.name & ".pdf"
if wsA.name <> "Top 25" and wsA.name <> "Top 10" then
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=**ActiveWorkbook.path & "\" & myFile, _**
(Filename:= fldrpath & myfile, _)
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
With ActiveSheet
CF = .Cells.Find(What:="*", After:=Range("A1"),
LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByColumns,
SearchDirection:=xlPrevious).Column
CV = .Cells.Find(What:="*", After:=Range("A1"),
LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByColumns,
SearchDirection:=xlPrevious).Column
RF = .Cells.Find(What:="*", After:=Range("A1"),
LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows,
SearchDirection:=xlPrevious).Row
RV = .Cells.Find(What:="*", After:=Range("A1"),
LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows,
SearchDirection:=xlPrevious).Row
Col = Application.WorksheetFunction.Max(CF, CV)
Rw = Application.WorksheetFunction.Max(RF, RV)
.PageSetup.Orientation = xlLandscape
.PageSetup.Zoom = False
.PageSetup.FitToPagesTall = False
.PageSetup.FitToPagesWide = 1
.PageSetup.PrintArea = "$A$1:" & Cells(Rw, Col).Address
End With
End if
Next wsA
response = MsgBox(prompt:="PDF's created and saved", Buttons:=vbOKOnly, Title:="Exported to PDF and saved in new folder")

Using VBA to print to PDF existing macro

So i found this code online and was able to edit it to do what i want EXCEPT save as a PDF it currently set to only show me a print preview. Can someone explain how to edit this to save as a PDF with the File name being what ends up appearing in cell "A2"
Sub testme()
Dim TempWks As Worksheet
Dim wks As Worksheet
Dim myRng As Range
Dim myCell As Range
'change to match your worksheet name
Set wks = Worksheets("Sheet3")
Set TempWks = Worksheets.Add
wks.AutoFilterMode = False 'remove the arrows
'assumes headers only in row 1
wks.Columns(1).AdvancedFilter Action:=xlFilterCopy, _
CopyToRange:=TempWks.Range("A1"), Unique:=True
With TempWks
Set myRng = .Range("a2", .Cells(.Rows.Count, "A").End(xlUp))
End With
With wks
For Each myCell In myRng.Cells
.UsedRange.AutoFilter Field:=1, Criteria1:=myCell.Value
Dim MyFileName As Variant
Dim MyfilePath As Variant
Dim rng As Range
Set wks = Worksheets("Sheet3")
Set rng = wks.Cells(2, 1)
MyfilePath = "C:\Users\mmunoz\Desktop\Teresa" 'this is whatever location you wish to save in
MyFileName = MyfilePath & "\" & rng.Value & ".pdf" 'You can do the below in just a couple of lines, but this is way more effective and stops issues later on
ChDir _
MyfilePath ' hold your save location
wks.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
MyFileName, Quality:= _
xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False 'did you want to open the file after saving?
Next myCell
End With
Application.DisplayAlerts = False
TempWks.Delete
Application.DisplayAlerts = True
End Sub
I have a bunch of data that I need to filter to show only a client's lines of data and save that as a PDF to send to the client.
Thanks,
This is the gist of what you want. I've added comments to explain
Dim MyFileName As Variant
Dim MyfilePath As Variant
Dim rng As Range
Set rng = wks.Cells(2, 1)
MyfilePath = "N:\Desktop" 'this is whatever location you wish to save in
MyFileName = MyfilePath & "\" & rng.Value & ".pdf" 'You can do the below in just a couple of lines, but this is way more effective and stops issues later on
ChDir _
MyfilePath ' hold your save location
wks.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
MyFileName, Quality:= _
xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=True 'did you want to open the file after saving?
Option Explicit
Sub testme()
Dim TempWks As Worksheet
Dim wks As Worksheet
Dim myRng As Range
Dim myCell As Range
'change to match your worksheet name
Set wks = Worksheets("Sheet3")
Set TempWks = Worksheets.Add
wks.AutoFilterMode = False 'remove the arrows
'assumes headers only in row 1
wks.Columns(1).AdvancedFilter Action:=xlFilterCopy, _
CopyToRange:=TempWks.Range("A1"), Unique:=True
With TempWks
Set myRng = .Range("a2", .Cells(.Rows.Count, "A").End(xlUp))
End With
With wks
For Each myCell In myRng.Cells
.UsedRange.AutoFilter Field:=1, Criteria1:=myCell.Value
Dim MyFileName As Variant
Dim MyfilePath As Variant
Dim rng As Range
Set rng = wks.Cells(2, 1)
MyfilePath = "C:\Users\mmunoz\Desktop\Teresa" 'File Location
MyFileName = MyfilePath & "\" & myCell.Value & ".pdf" 'File Name
ChDir _
MyfilePath
wks.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
MyFileName, Quality:= _
xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Next myCell
End With
Application.DisplayAlerts = False
TempWks.Delete
Application.DisplayAlerts = True
End Sub

Add specific CSV to workbook in VBA

I have a an Excel workbook and I want to add a specific CSV as a new sheet and then convert it in a table.
Here is my VBA code, this works fine, the problem is that then when I want to convert the sheet into a tab then Excel give me this error:
A Table cannot overlap a range that contains a Pivot Table report,query results, protected cells or another table.
Sub Macro8()
'
'
Dim strPath As String
Dim strFile As String
'
strPath = "Q:\myfolder\"
strFile = Dir(strPath & "filename" & Format(Now(), "YYYYMMDD") & ".csv")
Do While strFile <> ""
With ActiveWorkbook.Worksheets.Add
With .QueryTables.Add(Connection:="TEXT;" & strPath & strFile, _
Destination:=.Range("A1"))
.Parent.Name = Replace(strFile, ".csv", "")
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End With
strFile = Dir
Loop
End Sub
Sub A_SelectAllMakeTable()
Dim tbl As ListObject
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.Name = "OPEN"
tbl.TableStyle = "TableStyleMedium15"
End Sub
Can someone help me please?
A Table cannot overlap a range that contains a Pivot Table report,query results, protected cells or another table.
You need to break the querytable connection first else you will get the error that you are getting. is this what you are trying?
Sub A_SelectAllMakeTable()
Dim tbl As ListObject
Dim rng As Range
Dim ws As Worksheet
Dim lCol As Long, lRow As Long
Set ws = ActiveSheet
With ws
'~~> Delete the connection
For Each Cn In .QueryTables
Cn.Delete
Next Cn
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
'~~> Find last row and column to construct your range
lRow = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
lCol = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
Set rng = .Range(.Cells(1, 1), .Cells(lRow, lCol))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.Name = "OPEN"
tbl.TableStyle = "TableStyleMedium15"
End If
End With
End Sub

Excel vba if value is in column then [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to make a macro via an if then else function (maybe make use of a loop).
I have two separate files, named "orderregistratie" + "werkorder template".
I want to search in column A of sheets("datablad") in orderregistratie for the value sheets("export datablad").Range("A2") that is in werkorder template.
If this value exists in column A then copy the row of A2 from export datablad and paste it in the row where the value is found.
If it doesn't already exist I want to insert a new row at A2 in orderregistratie and copy the row of A2 from export datablad in the new row.
My VBA knowledge is not really good and I can't write the macro by myself. Is there anyone who can help me write it?
Give this a try. I'll adjust as needed. Just be double check if both workbooks are saved to your desktop.
Option Explicit
Private wkbOrderReg As Workbook, _
wkbOrderWork As Workbook, _
wkb As Workbook
Private wsOBJ As Worksheet, _
ws As Worksheet
Private rngSearch As Range, _
rngRow As Range, _
rng As Range, _
r As Range
Private strSearch As String
Public Sub DarudeSandStorm()
Dim LastRow As Long, _
LastColumn As Long
Dim arr As Variant
With Application.Workbooks
Set wkbOrderReg = .Open(Filename:=strVar("orderregistratie.xlsx"))
Set wkbOrderWork = .Open(Filename:=strVar("werkorder template.xlsx"))
End With
With wkbOrderWork
For Each ws In .Worksheets
Set wsOBJ = ws
If UCase$(wsOBJ.Name) = UCase$("export datablad") Then
With wsOBJ
Set rng = .Range(.Cells(2, 1), .Cells(2, 1))
strSearch = rng.Value
LastColumn = getLAST_COLUMN(wsOBJ)
Set rngRow = .Range(.Cells(2, 1), .Cells(2, LastColumn))
End With
arr = rngRow
Exit For
End If
Next ws
End With
With wkbOrderReg
For Each ws In .Worksheets
Set wsOBJ = ws
If UCase$(wsOBJ.Name) = UCase$("export datablad") Then
With wsOBJ
LastRow = getLAST_ROW(wsOBJ)
Set rngSearch = .Range(.Cells(1, 1), .Cells(LastRow, 1))
End With
For Each r In rngSearch
If UCase$(r.Value) = UCase$(strSearch) Then
r = arr
End If
Next r
End If
Next ws
End With
With Application
For Each wkb In .Workbooks
If Not wkb = .ThisWorkbook Then
With .Workbooks(wkb.Name)
.Save
.Close
End With
End If
Next wkb
End With
End Sub
Private Function getLAST_COLUMN(objWS As Worksheet) As Long
Dim wsDES As Worksheet, _
wkbSUB As Workbook, _
rngCHECK As Range
Set rngCHECK = objWS.Cells.Find(What:="*", _
After:=Range("A1"), _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False)
If Not rngCHECK Is Nothing Then
getLAST_COLUMN = objWS.Cells.Find("*", _
Range("A1"), _
xlFormulas, _
, _
xlByColumns, _
xlPrevious).Column
Else
getLAST_COLUMN = 1
End If
End Function
Private Function getLAST_ROW(objWS As Worksheet) As Long
Dim wsDES As Worksheet, _
wkbSUB As Workbook, _
rngCHECK As Range
Set rngCHECK = objWS.Cells.Find(What:="*", _
After:=Range("A1"), _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False)
If Not rngCHECK Is Nothing Then
getLAST_ROW = objWS.Cells.Find("*", _
Range("A1"), _
xlFormulas, _
, _
xlByRows, _
xlPrevious).Row
Else
getLAST_ROW = 1
End If
End Function
Private Function strVar(ByRef str As String) As String
strVar = Environ("Userprofile") & "\Desktop\" & str
End Function
#Mischa Urlings for this example i have save both workbooks ("orderregistratie" + "werkorder template") on my desktop so you must change their path on the code.
Option Explicit
Sub test()
Dim WbO As Workbook
Dim WbW As Workbook
Dim i As Long
Dim LRA As Long
Dim RowToCopy As Long
Dim Rowstr As Long
Dim Searchstr As String
Dim Address As Range
Dim Searchrng As Range
Workbooks.Open Filename:="C:\Users\xxxx\Desktop\" & "orderregistratie.xlsx" '<= Open Workbooks (for this example files are stored on desktop
Workbooks.Open Filename:="C:\Users\xxxx\Desktop\" & "werkorder template.xlsx"
Set WbO = Workbooks("orderregistratie.xlsx") '<= Set workbook to variables
Set WbW = Workbooks("werkorder template.xlsx")
LRA = WbW.Worksheets("export datablad").Range("A" & Rows.Count).End(xlUp).Row '<= Find Lastrow
For i = 2 To LRA '<= Loop column A (Workbook:werkorder template)
Searchstr = WbW.Worksheets("export datablad").Range("A" & i).Value '<= Set what to search for
Rowstr = i '<= Searchstr row
Set Searchrng = WbO.Worksheets("datablad").Columns("A") '<= Set where to search for
Set Address = Searchrng.Find(What:=Searchstr, LookAt:=xlWhole) '<= Result of the search
If Address Is Nothing Then
'If what we search for not found
WbO.Worksheets("datablad").Rows("2").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
WbW.Worksheets("export datablad").Rows(Rowstr).EntireRow.Copy
WbO.Worksheets("datablad").Rows(2).PasteSpecial Paste:=xlPasteValues
Else
'If what we search for found
RowToCopy = Address.Row '<= Where we find the Searchstr
WbW.Worksheets("export datablad").Rows(i).EntireRow.Copy
WbO.Worksheets("datablad").Rows(RowToCopy).PasteSpecial Paste:=xlPasteValues
End If
Next i
With WbO
.Save
.Close '<= Close open workbooks
End with
With WbW
.Save
.Close '<= Close open workbooks
End with
End Sub

Macro creating a new workbork instead of adding a sheet

The following Macro was intended to get specific data for a date range. While it does this, I wanted it displayed within the same workbook on another sheet, instead a new workbook is created. Any idea on how I can fix this?
Public Sub PromptUserForInputDates()
Dim strStart As String, strEnd As String, strPromptMessage As String
strStart = InputBox("Please enter the start date")
If Not IsDate(strStart) Then
strPromptMessage = "Not Valid Date"
MsgBox strPromptMessage
Exit Sub
End If
strEnd = InputBox("Please enter the end date")
If Not IsDate(strStart) Then
strPromptMessage = "Not Valid Date"
MsgBox strPromptMessage
Exit Sub
End If
Call CreateSubsetWorkbook(strStart, strEnd)
End Sub
Public Sub CreateSubsetWorkbook(StartDate As String, EndDate As String)
Dim wbkOutput As Workbook
Dim wksOutput As Worksheet, wks As Worksheet
Dim lngLastRow As Long, lngLastCol As Long, lngDateCol As Long
Dim rngFull As Range, rngResult As Range, rngTarget As Range
lngDateCol = 4
Set wbkOutput = Workbooks.Add
For Each wks In ThisWorkbook.Worksheets
With wks
Set wksOutput = wbkOutput.Sheets.Add
wksOutput.Name = wks.Name
Set rngTarget = wksOutput.Cells(1, 1)
lngLastRow = .Cells.Find(What:="*", LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row
lngLastCol = .Cells.Find(What:="*", LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
Set rngFull = .Range(.Cells(1, 1), .Cells(lngLastRow, lngLastCol))
With rngFull
.AutoFilter Field:=lngDateCol, _
Criteria1:=">=" & StartDate, _
Criteria2:="<=" & EndDate
Set rngResult = rngFull.SpecialCells(xlCellTypeVisible)
rngResult.Copy Destination:=rngTarget
End With
.AutoFilterMode = False
If .FilterMode = True Then
.ShowAllData
End If
End With
Next wks
MsgBox "Data Transferred!"
End Sub
You're defining Set wbkOutput = Workbooks.Add which will always create a new workbook. Instead, Set wbkOutput = the workbook where you want the output to be.
Note that your assignment of wksOutput.Name = wks.Name will fail (two worksheets cannot have same name), so I've commented it out for now and you can revise that statement as needed.
Replace all references to wbkOutput with ThisWorkbook
Public Sub CreateSubsetWorkbook(StartDate As String, EndDate As String)
Dim wksOutput As Worksheet, wks As Worksheet
Dim lngLastRow As Long, lngLastCol As Long, lngDateCol As Long
Dim rngFull As Range, rngResult As Range, rngTarget As Range
lngDateCol = 4
For Each wks In ThisWorkbook.Worksheets
With wks
Set wksOutput = ThisWorkbook.Sheets.Add
' This is not allowed, you can make some change to the name but it cannot be the same name worksheet
' >>> wksOutput.Name = wks.Name
Set rngTarget = wksOutput.Cells(1, 1)
lngLastRow = .Cells.Find(What:="*", LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row
lngLastCol = .Cells.Find(What:="*", LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
Set rngFull = .Range(.Cells(1, 1), .Cells(lngLastRow, lngLastCol))
With rngFull
.AutoFilter Field:=lngDateCol, _
Criteria1:=">=" & StartDate, _
Criteria2:="<=" & EndDate
Set rngResult = rngFull.SpecialCells(xlCellTypeVisible)
rngResult.Copy Destination:=rngTarget
End With
.AutoFilterMode = False
If .FilterMode = True Then
.ShowAllData
End If
End With
Next wks
End Sub

Resources