To provide a snapshot of how the code functions:
User Clicks button to Import Job Folder
File Path Selection Opens and User Selects File
VBA Imports Specified Cell Values from Job File and Pastes link to sheet.
Everything works fine except once in a while I get a error that says "No link to paste" and reference the ActiveSheet.Paste Link:=True Line but if I hit the runsub button on the VBA code editor it works. I don't know why I get this Error sometimes. Is there a way to make the code rerun on that error?
The Error occurs at any of the ActiveSheet.Paste Link:=True in the code shown below, again at random and at any of the Import Selections (Project Name or Client Name or Project Name etc)
'Imports Project#
sourcewb.Sheets("Estimate").Range("PROJECT_NUMBER").Copy 'project# info is located on "Reporting" tab
summarywb.ActiveSheet.Activate
summarywb.ActiveSheet.Cells(NewRow, 1).Select
ActiveSheet.Paste Link:=True
'Imports Client Name
sourcewb.Sheets("Estimate").Range("PROJECT_CLIENT").Copy 'C3 is where client name info is located on "Reporting"
summarywb.ActiveSheet.Activate
summarywb.ActiveSheet.Cells(NewRow, 2).Select
ActiveSheet.Paste Link:=True
'Imports Project Name
sourcewb.Sheets("Estimate").Range("PROJECT_NAME").Copy 'C2 is where project name info is located on "Reporting"
summarywb.ActiveSheet.Activate
summarywb.ActiveSheet.Cells(NewRow, 3).Select
ActiveSheet.Paste Link:=True
'Imports Latest Revision Date
sourcewb.Sheets("Reporting").Range("O5").Copy 'P5 is where project name info is located on "Reporting"
summarywb.ActiveSheet.Activate
summarywb.ActiveSheet.Cells(NewRow, 19).Select
ActiveSheet.Paste Link:=True
0
'Imports data from Project Total line
sourcewb.Sheets("Reporting").Range("C24:Q24").Copy 'Row 24 is where Project Total line is located on "Reporting"
PTRange = "D" & NewRow & ":" & "R" & NewRow
summarywb.ActiveSheet.Activate
summarywb.ActiveSheet.Range(PTRange).Select
ActiveSheet.Paste Link:=True
Below is the full code:
'///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
'
'This code imports select data from specified project's cost tracking spread sheet.
'
'///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Sub ImportProjectStatus()
'Minimize runtime
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'Initialize Variables
Dim summarywb As Workbook
Dim sourcewb As Workbook
Dim currentVer As String
Dim FirstRow As Long
Dim LastRow As Long
Dim NewRow As Long
Dim NewJobNumber As String
Dim PTRange As String
'Set initial values
Set summarywb = ThisWorkbook
currentVer = "0.8.0"
'Open file selection dialog box
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
openFile = Application.FileDialog(msoFileDialogOpen).Show
If openFile <> 0 Then
sourcewbpath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1) 'Select the corresponding master file
Else
sourcewbpath = ""
Exit Sub
End If
Set sourcewb = Workbooks.Open(sourcewbpath)
'Error Handling - If there is no reporting tab on a tracking sheet
On Error GoTo NoReportTabError
'Searches for first non-blank row with data
FirstRow = summarywb.ActiveSheet.Cells.Find(What:="Project #", After:=Range("A1"), LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False).Row + 1
'Searches for last non-blank row
LastRow = summarywb.ActiveSheet.Cells.Find(What:="*", After:=Range("A1"), LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False).Row
'Sets Row to which new data will be imported
NewRow = LastRow + 1
'Checks if to-be imported job number is a duplicate
NewJobNumber = sourcewb.Sheets("Reporting").Range("P2")
If DuplicateCheck(summarywb, FirstRow, LastRow, NewRow, NewJobNumber) = 1 Then
If MsgBox(NewJobNumber & " already exists. Continue?", vbYesNo, "Confirm") = vbNo Then
'Close sourcewb
sourcewb.Close savechanges:=False
'Display back on
Application.ScreenUpdating = True
Application.DisplayAlerts = True
'Abort message
MsgBox "Job not added."
Exit Sub
End If
End If
'Imports Project#
sourcewb.Sheets("Estimate").Range("PROJECT_NUMBER").Copy 'project# info is located on "Reporting" tab
summarywb.ActiveSheet.Activate
summarywb.ActiveSheet.Cells(NewRow, 1).Select
ActiveSheet.Paste Link:=True
'Imports Client Name
sourcewb.Sheets("Estimate").Range("PROJECT_CLIENT").Copy 'C3 is where client name info is located on "Reporting"
summarywb.ActiveSheet.Activate
summarywb.ActiveSheet.Cells(NewRow, 2).Select
ActiveSheet.Paste Link:=True
'Imports Project Name
sourcewb.Sheets("Estimate").Range("PROJECT_NAME").Copy 'C2 is where project name info is located on "Reporting"
summarywb.ActiveSheet.Activate
summarywb.ActiveSheet.Cells(NewRow, 3).Select
ActiveSheet.Paste Link:=True
'Imports Latest Revision Date
sourcewb.Sheets("Reporting").Range("O5").Copy 'P5 is where project name info is located on "Reporting"
summarywb.ActiveSheet.Activate
summarywb.ActiveSheet.Cells(NewRow, 19).Select
ActiveSheet.Paste Link:=True
'Imports data from Project Total line
sourcewb.Sheets("Reporting").Range("C24:Q24").Copy 'Row 24 is where Project Total line is located on "Reporting"
PTRange = "D" & NewRow & ":" & "R" & NewRow
summarywb.ActiveSheet.Activate
summarywb.ActiveSheet.Range(PTRange).Select
ActiveSheet.Paste Link:=True
'Adds "N" to closed column
summarywb.ActiveSheet.Cells(NewRow, 20) = "N"
CleanExit:
'Line to display which line a new job was added to
MsgBox NewJobNumber & " added to line " & NewRow
'Close sourcewb
sourcewb.Close savechanges:=False
'Refresh Data (Note. Refreshes all links)
RefreshAllLinks
'Display back on
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Exit Sub
NoReportTabError:
MsgBox "No Reporting tab found on the specified Tracking workbook. Closing Macro."
'Close sourcewb
sourcewb.Close savechanges:=False
'Display back on
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Exit Sub
End Sub
'///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
'
'This code checks for job numbers that are duplicate of the one to be added.
'
'///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Private Function DuplicateCheck(summarywb, FirstRow, LastRow, NewRow, NewJobNumber)
Dim CheckCell As String
summarywb.ActiveSheet.Activate
For i = FirstRow To LastRow
Range("A" & i).Select
Selection.Copy
Range("A" & NewRow).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=Flase, Transpose:=False
CheckCell = Cells(NewRow, 1).Value
If CheckCell = NewJobNumber Then
DuplicateCheck = 1
Range("A" & NewRow).Clear
Exit Function
End If
Range("A" & NewRow).Clear
Next i
End Function
'///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
'
'This code refreshes all links in the active worksheet.
'
'///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Sub RefreshAllLinks()
'Minimize runtime
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'Initialize Variables
Dim summarywb As Workbook
'Set initial values
Set summarywb = ThisWorkbook
'Refresh all linked data
summarywb.ActiveSheet.Activate
summarywb.UpdateLink Name:=summarywb.LinkSources
'Display back on
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
'///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
'
'This code moves highlighted line(s) of data from current to archive tab.
'
'///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Sub ArchiveData()
'Minimize runtime
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'Initialize Variables
Dim summarywb As Workbook
Dim LastRow As Long
Dim NewRow As Long
'Set initial values
Set summarywb = Workbooks("Project Status Summary.xlsm")
'Asks for confirmation
If MsgBox("Archive highlighted job(s)?", vbYesNo, "Confirm") = vbNo Then
'Display back on
Application.ScreenUpdating = True
Application.DisplayAlerts = True
'Abort message
MsgBox "Job(s) not archived."
Exit Sub
End If
'Finds last non-blank row on Archive sheet
Worksheets("Archive").Activate
LastRow = summarywb.Sheets("Archive").Cells.Find(What:="*", After:=Range("A1"), LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False).Row
'Assigns row number for a new line
NewRow = LastRow + 1
'Copies and pastes data from Current tab to Archive tab
Worksheets("Current").Activate
Selection.Copy
Worksheets("Archive").Activate
Range("A" & NewRow).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=Flase, Transpose:=False
''Displays confirmation message
MsgBox ("Job(s) archived.")
'Display back on
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
If the copy fails intermittently, it might be a race condition. Here's a little snippet that retries the paste a few times:
Sub PasteEx()
On Error Resume Next
Err.Clear
ActiveSheet.Paste Link:=True
If Err.Number = 0 Then
GoTo PasteEx_Exit
Else
For i = 1 To 3
Err.Clear
ActiveSheet.Paste Link:=True
If Err.Number = 0 Then
GoTo PasteEx_Exit
End If
Application.Wait Now + TimeValue("0:00:01") ' Adjust as needed
Next i
End If
On Error GoTo 0
Err.Raise 1004
PasteEx_Exit:
On Error GoTo 0
End Sub
Add this method and replace your ActiveSheet.Paste Link:=True with PasteEx.
There is a delay in there. Adjust it as needed.
Since I can't reproduce your conditions, I'm not sure if it will help you. Give it a try!
Related
This is a screenshot of my excel doc.
I want to apply filters based on values: Bimbo Mexico, Bimbo Canada and copy and paste the values(from column A & B) in a new sheet. I want to do this using macro as I am building a template for a client. Is there a way to do this? I know it can be done manually using filters manually but I want it to be based on a macro
I want the output like this:
I used recording macro and this is the macro I got,
Sub RecordedMacro()
'
' RecordedMacro Macro
'
' Keyboard Shortcut: Ctrl+l
'
Sheets("report").Select
Range("C1").Select
ActiveSheet.Range("$A$1:$S$1001").AutoFilter Field:=3, Criteria1:="Barcel"
Columns("L:L").Select
Selection.Copy
Sheets("SkuRounds").Select
Columns("S:S").Select
ActiveSheet.Paste
Sheets("report").Select
ActiveSheet.Range("$A$1:$S$1001").AutoFilter Field:=3, Criteria1:= _
"Bimbo Canada"
Columns("L:L").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("SkuRounds").Select
Columns("T:T").Select
ActiveSheet.Paste
Sheets("report").Select
ActiveSheet.Range("$A$1:$S$1001").AutoFilter Field:=3, Criteria1:= _
"Bimbo Latin Centro"
Columns("L:L").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("SkuRounds").Select
Columns("U:U").Select
ActiveSheet.Paste
Sheets("report").Select
ActiveSheet.Range("$A$1:$S$1001").AutoFilter Field:=3, Criteria1:= _
"Bimbo México"
Columns("L:L").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("SkuRounds").Select
Columns("V:V").Select
ActiveSheet.Paste
End Sub
I am copying data from sheet(report) to sheet(skurounds)
Give this a try:
Sub tgr()
Dim wb As Workbook
Dim wsReport As Worksheet
Dim wsSKU As Worksheet
Dim dictUnqCompanies As Object
Dim aCompanies As Variant
Dim vCompany As Variant
Dim lDestCol As Long
Set wb = ActiveWorkbook
Set wsReport = wb.Sheets("report")
Set wsSKU = wb.Sheets("skurounds")
Set dictUnqCompanies = CreateObject("Scripting.Dictionary")
lDestCol = wsSKU.Columns("S").Column
'Clear previous results
wsSKU.Range(wsSKU.Cells(1, "S"), wsSKU.Cells(1, wsSKU.Columns.Count)).EntireColumn.Clear
With wsReport.Range("C2", wsReport.Cells(wsReport.Rows.Count, "C").End(xlUp))
If .Row < 2 Then Exit Sub 'No data
If .Rows.Count = 1 Then
'Only 1 row of data
wsSKU.Cells(1, lDestCol).Value = .Value
.Parent.Cells(.Row, "L").Copy wsSKU.Cells(2, lDestCol)
Exit Sub
Else
aCompanies = .Value
End If
End With
For Each vCompany In aCompanies
If Not dictUnqCompanies.exists(vCompany) Then
dictUnqCompanies.Add vCompany, vCompany
With wsReport.Range("C1", wsReport.Cells(wsReport.Rows.Count, "C").End(xlUp))
.AutoFilter 1, vCompany
wsSKU.Cells(1, lDestCol).Value = vCompany
Intersect(.Parent.Columns("L"), .Offset(1).EntireRow).Copy wsSKU.Cells(2, lDestCol)
lDestCol = lDestCol + 1
.AutoFilter
End With
End If
Next vCompany
End Sub
I'm running a Macro that creates a new workbook and a tab in that workbook based on a dropdown selection. I'm running into issues with my conditional formatting. When I run the macro the conditional formatting rules are there but the color output changes. For example I have a conditional formatting that changes a number green based on another value but after running the macro the color changes to Orange. Doe's anyone know why?
Here's the code that I'm running
Sub BusinessPlan_Create()
Dim cell As Range
Dim counter As Long
Dim Dashboard As Worksheet
Dim newWB As Workbook
Dim wb1 As Workbook
Set wb1 = ThisWorkbook
Set newWB = Workbooks.Add
Set Dashboard = wb1.Sheets("Facility View")
Application.DisplayAlerts = False
For Each cell In wb1.Worksheets("dd").Range("$B3:$B87")
If cell.Value = "" Then
counter = counter + 1
Application.StatusBar = "Processing file: " & counter & "/1042"
Else
counter = counter + 1
Application.StatusBar = "Processing file: " & counter & "/1042"
With Dashboard
.Range("$B$1").Value = cell.Value
With wb1
.Worksheets("Facility View").Copy After:=newWB.Worksheets(1)
ActiveSheet.Cells.Copy
ActiveSheet.Range("A1").PasteSpecial Paste:=xlPasteSpecialOperationAdd
ActiveSheet.Name = cell.Value
End With
Application.CutCopyMode = False
End With
End If
Next cell
newWB.Activate
Call SortWorkBook2
Application.DisplayAlerts = True
Range("C6:D6").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Columns("C:C").EntireColumn.AutoFit
Columns("D:D").EntireColumn.AutoFit
Range("C4").Select
Application.CutCopyMode = False
End Sub
I am currently having an issue getting the data from one sheet to paste special into another sheet, I am trying to consolidate multiple files (same headers, differing number of rows) into one master sheet containing all the rows. At the moment I'm doing that by opening all the files, pulling in the tabs I want, copy and pasting the data, and then deleting the tabs. Yes I am sure there is an easier way, but I'm very new to VBA and am learning on the fly..here's what I have so far:
Sub ConsolidateSheets()
' open each file in folder
Dim Folder As String
Dim Files As String
Folder = "C:\Users\212411103\Documents\Risk Project Tracker\Risk Project Tracker Monthly\Monthly Data"
Files = Dir(Folder & "\*.xls")
Do While Files <> ""
Workbooks.Open Filename:=Folder & "\" & Files
Files = Dir
Loop
' pull in Risk Project Tracker tab from each file to new workbook
Dim wkb As Workbook
Dim sWksName As String
sWksName = "Risk Project Tracker"
For Each wkb In Workbooks
If wkb.Name <> ThisWorkbook.Name Then
wkb.Worksheets(sWksName).Copy _
Before:=ThisWorkbook.Sheets(1)
End If
Next
Set wkb = Nothing
Dim J As Integer
' add new sheet for combined data
On Error Resume Next
Sheets(1).Select
Worksheets.Add
Sheets(1).Name = "New Month"
' paste headers from first two rows into new sheet "New Month"
Sheets(2).Select
Range("A1:AH2").Select
Selection.Copy
Sheets("New Month").Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
ActiveSheet.Paste
Range("A1").Select
' work through sheets
For J = 2 To Sheets.Count ' from sheet 2 to last sheet
Sheets(J).Activate ' make the sheet active
Rows("1:2").Select
Selection.Delete Shift:=xlUp
Range("A1:AH500").Select
Selection.Copy
Sheets("New Month").Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Range("A1").Select
Next
' Delete tabs that are no longer needed i.e. the tabs from the 17 files
' For Each ws in Sheets
' Application.DisplayAlerts=False
' If ws.Name <> "New Month" Then ws.delete
' Next
' Application.DisplayAlerts=True
End Sub
It appears that the primary reason you are specifying the Range .PasteSpecial method is the carry-over of column widths which is done for every tab. Perhaps cycling through A:AH once and setting the column widths should be sufficient.
Sub ConsolidateSheets2()
Dim fldr As String, fn As String, sWksName As String, sNewWksName As String
Dim ws As Worksheet, wkb As Workbook
On Error GoTo bm_Safe_Exit
Application.ScreenUpdating = False
Application.EnableEvents = False
sWksName = "Risk Project Tracker"
fldr = "C:\Users\212411103\Documents\Risk Project Tracker\Risk Project Tracker Monthly\Monthly Data"
fn = Dir(fldr & "\*.xls")
sNewWksName = "New Month"
With ThisWorkbook
Do While fn <> ""
Set wkb = Workbooks.Open(Filename:=fldr & Chr(92) & fn)
If IsObject(wkb.Worksheets(sWksName)) Then
wkb.Worksheets(sWksName).Copy _
Before:=ThisWorkbook.Sheets(1 - CBool(Sheets(1).Name = sNewWksName))
On Error GoTo bm_Need_New_Month_ws
With .Worksheets(sNewWksName)
On Error GoTo bm_Safe_Exit
.Parent.Sheets(2).Range("A3:AH502").Copy _
Destination:=.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
End With
End If
wkb.Close False
fn = Dir
Loop
Application.DisplayAlerts = False
Do While Sheet.Count > 1: Sheets(2).Delete: Loop
End With
GoTo bm_Safe_Exit
bm_Need_New_Month_ws:
If Err.Number = 9 Then
With ThisWorkbook.Worksheets.Add(Before:=ThisWorkbook.Sheets(1))
.Name = sNewWksName
.Move Before:=Sheets(1)
.Parent.Sheets(2).Range("A1:AH2").Copy _
Destination:=.Range("A1")
For c = .Columns("AH:AH").Column To 1 Step -1
.Columns(c).ColumnWidth = _
.Parent.Sheets(2).Columns(c).ColumnWidth
Next c
End With
Resume
End If
bm_Safe_Exit:
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
I have the following VBA code that takes a single row from Sheet "Tabled data", copies the data, then pastes the data into the next available row in Sheet "Running list". However the original row has formulas and I need the values to paste, not the formulas. I've seen numerous ways to do it with Range.PasteSpecial but this code didn't use Range and I'm not sure how to incorporate it.
Note: I modified this code from here: http://msdn.microsoft.com/en-us/library/office/ff837760(v=office.15).aspx. It originally had an IF statement to match content in a cell then paste it in a certain sheet according to the content in the cell. I only had one sheet to copy to and didn't need the IF. I don't really need to find the last row of data to copy either as it will only ever be one row with range of A2:N2. But if I take out the FinalRow section and the For and replace with Range("A2:N2") it doesn't work so I left those in.
Any guidance on how to add in the PasteValues property without making this more complicated? I'm also open to simplification of the For or FinalRow variable such as using Range. I'm only sort of familiar with VBA, having done a few things with it, but usually after much searching and modifying code.
Public Sub CopyData()
Sheets("Tabled data").Select
' Find the last row of data
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
' Loop through each row
For x = 2 To FinalRow
ThisValue = Cells(x, 1).Value
Cells(x, 1).Resize(1, 14).Copy
Sheets("Running list").Select
NextRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
Cells(NextRow, 1).Select
ActiveSheet.Paste
Sheets("Tabled data").Select
Next x
End Sub
Hopefully we can actually make this more simple.
Public Sub CopyRows()
Sheets("Sheet1").UsedRange.Copy
lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
'check if the last cell found is empty
If IsEmpty(ActiveSheet.Cells(lastrow, 1)) = True Then
'if it is empty, then we should fill it
nextrow = lastrow
Else
'if it is not empty, then we should not overwrite it
nextrow = lastrow + 1
End If
ActiveSheet.Cells(nextrow, 1).Select
ActiveSheet.Paste
End Sub
edit: I expanded it a little so that there won't be a blank line at the top
I found a working solution. I recorded a macro to get the paste special in there and added the extra code to find the next empty row:
Sub Save_Results()
' Save_Results Macro
Sheets("Summary").Select 'renamed sheets for clarification, this was 'Tabled data'
'copy the row
Range("Table1[Dataset Name]").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
' paste values into the next empty row
Sheets("Assessment Results").Select
Range("A2").Select
NextRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
Cells(NextRow, 1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
' Return to main sheet
Sheets("Data Assessment Tool").Select
End Sub
Just copy the data all at once, no need to do it a row at a time.
Sub CopyData()
With ThisWorkbook.Sheets("Tabled data")
Dim sourceRange As Range
Set sourceRange = .Range(.Cells(2, 1), .Cells(getLastRow(.Range("A1").Parent), 14))
End With
With ThisWorkbook.Sheets("Running list")
Dim pasteRow As Long
Dim pasteRange As Range
pasteRow = getLastRow(.Range("A1").Parent) + 1
Set pasteRange = .Range(.Cells(pasteRow, 1), .Cells(pasteRow + sourceRange.Rows.Count, 14))
End With
pasteRange.Value = sourceRange.Value
End Sub
Function getLastRow(ws As Worksheet, Optional colNum As Long = 1) As Long
getLastRow = ws.Cells(ws.Rows.Count, colNum).End(xlUp).Row
End Function
Private Sub Load_Click()
Call ImportInfo
End Sub
Sub ImportInfo()
Dim FileName As String
Dim WS1 As Worksheet
Dim WS2 As Worksheet
Dim ActiveListWB As Workbook
Dim check As Integer
'Application.ScreenUpdating = False
Set WS2 = ActiveWorkbook.Sheets("KE_RAW")
confirm = MsgBox("Select (.xlsx) Excel file for Data transfer." & vbNewLine & "Please ensure the sheets are named Sort List, Second and Third.", vbOKCancel)
If confirm = 1 Then
FileName = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls*),*.xls*", _
Title:="Select Active List to Import", MultiSelect:=False)
If FileName = "False" Then
MsgBox "Import procedure was canceled"
Exit Sub
Else
Call CleanRaw
Set ActiveListWB = Workbooks.Open(FileName)
End If
Set WS1 = ActiveListWB.Sheets("Sort List")
WS1.UsedRange.Copy 'WS2.Range("A1")
' WS2.Range("A1").Select
WS2.UsedRange.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'WS2.Range ("A1")
ActiveWorkbook.Close False
'Call ClearFormulas
' Call RefreshAllPivotTables
Sheets("Key Entry Data").Select
'Sheets("Raw").Visible = False
'Application.ScreenUpdating = True
MsgBox "Data has been imported to workbook"
Else
MsgBox "Import procedure was canceled"
End If
Application.ScreenUpdating = True
End Sub
Sub CleanRaw()
Sheets("KE_RAW").Visible = True
Sheets("KE_RAW").Activate
ActiveSheet.Cells.Select
Selection.ClearContents
End Sub
I have the following code that copies one worksheet to another and pastes only values however the code that protects the sheet is not working? what am I doing wrong here?
Sub GetQuote()
Range("AK548").Select
Selection.Copy
Range("AK549").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Dim ws As Worksheet
Dim sDataOutputName As String
With Application
.Cursor = xlWait
.StatusBar = "Saving Quote & Proposal Sheet..."
.ScreenUpdating = False
' Copy specific sheets
' *SET THE SHEET NAMES TO COPY BELOW*
' Array("Sheet Name", "Another sheet name", "And Another"))
' Sheet names go inside quotes, seperated by commas
On Error GoTo ErrCatcher
Sheets(Array("Quote & Proposal")).Copy
On Error GoTo 0
' Paste sheets as values
' Remove External Links, Hperlinks and hard-code formulas
' Make sure A1 is selected on all sheets
For Each ws In ActiveWorkbook.Worksheets
ws.Cells.Copy
ws.[A1].PasteSpecial Paste:=xlValues
ws.Cells.Hyperlinks.Delete
Application.CutCopyMode = False
Cells(1, 1).Select
ws.Activate
Next ws
Cells(1, 1).Select
sDataOutputName = ThisWorkbook.Path & "\" & ThisWorkbook.Worksheets("Quote Questions").Range("AK545").Value & ".xlsx"
' Save it with the NewName and in the same directory as original
ActiveWorkbook.SaveCopyAs sDataOutputName
ActiveWorkbook.Protect Password:="12345"
ActiveWorkbook.Close SaveChanges:=False
.Cursor = xlDefault
.StatusBar = False
.ScreenUpdating = True
End With
Exit Sub
ErrCatcher:
MsgBox "Specified sheets do not exist within this workbook"
End Sub
You are protecting the workbook and setting the password, on the next line of code you closing the workbook but not saving the changes.
Your code is showing work book protection, not work sheet protection. If you want to protect the sheet, use worksheet protection:
ws.Protect Password:="12345", DrawingObjects:=True, Contents:=True, Scenarios:=True
'ADD AND REMOVE PARAMETERS AS YOU WANT THEM
I put in: ActiveSheet.Protect Password:="12345" just above the line of code: ActiveWorkbook.SaveCopyAs sDataOutputName and it worked!