This question already has answers here:
Copy from one workbook and paste into another
(2 answers)
Closed 5 years ago.
I am trying to copy all data from a workbook on my server and paste the values to B2 in another workbook.
This is what I have so far. It brings me to the workbook 2, but I have to manually select all and copy then paste in workbook 1.
Sub UpdateTSOM()
Application.ScreenUpdating = False
Dim LastRow As Long
Dim StartCell As Range
Set sht = Sheet5
Set reportsheet = Sheet5
Set StartCell = Range("B2")
'Refresh UsedRange
Worksheets("TSOM").UsedRange
'Find Last Row
LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
'Select Range
sht.Range("B2:B" & LastRow).Select
With Range("B2:B" & LastRow)
If MsgBox("Clear all Transmission Stock data?", vbYesNo) = vbYes Then
Worksheets("TSOM").Range("B2:N2000").ClearContents
MsgBox ("Notes:" & vbNewLine & vbNewLine & _ 'This is not needed if I can automate the copy and paste.
"Copy ALL" & vbNewLine & _
"Paste as Values")
End If
End With
Workbooks.Open "P:\ESO\1790-ORL\OUC\_Materials\Stock Status\Transmission Stock Status **-**-**.xlsx"
ThisWorkbook.Activate
reportsheet.Select
Range("B2").Select
whoa: 'If filename changes then open folder
Call Shell("explorer.exe" & " " & "P:\ESO\1790-ORL\OUC\_Materials\Stock Status", vbNormalFocus)
Range("B2").Select
Application.ScreenUpdating = True
End Sub
Thanks
A few guesses as you haven't provided all the details
Sub UpdateTSOM()
Application.ScreenUpdating = False
Dim LastRow As Long
Dim StartCell As Range
Dim sht As Worksheet
Dim wb As Workbook
Set sht = Sheet5
Set StartCell = sht.Range("B2")
'Find Last Row
LastRow = sht.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
If MsgBox("Clear all Transmission Stock data?", vbYesNo) = vbYes Then
Worksheets("TSOM").Range("B2:N2000").ClearContents
End If
Set wb = Workbooks.Open("P:\ESO\1790-ORL\OUC\_Materials\Stock Status\Transmission Stock Status **-**-**.xlsx")
wb.Sheets(1).UsedRange.Copy
StartCell.PasteSpecial xlValues
Application.ScreenUpdating = True
End Sub
Avoid SendKeys, and since you are pasting values only, you don't need to use either Copy or Paste/PasteSpecial.
With wsCopyFrom.Range("A1:N3000")
wsCopyTo.Range("B2").Resize(.Rows.Count, .Columns.Count).Value = .Value
End With
Here are several other ways to copy values from one file to another:
Copy from one workbook and paste into another
This is what I got to work. It brings up a select file folder and copies all the data from it into my current workbook. It then names B1 (my header) with the filename without the extension.
Sub UpdateTSOM()
Application.ScreenUpdating = False
Dim vFile As Variant
Dim wbCopyTo As Workbook
Dim wsCopyTo As Worksheet
Dim wbCopyFrom As Workbook
Dim wsCopyFrom As Worksheet
Dim s As String
Set mycell = Worksheets("TSOM").Range("B1")
Set wbCopyTo = ActiveWorkbook
Set wsCopyTo = ActiveSheet
If MsgBox("Update transmission Stock Status data?", vbYesNo) = vbYes Then
Worksheets("TSOM").Range("B2:N3000").ClearContents
Else: Exit Sub
End If
'Locate file to copy data from
vFile = Application.GetOpenFilename("Excel Files (*.xl*)," & _
"*.xl*", 1, "Select Excel File", "Open", False)
'Assign filename to Header
s = Mid(vFile, InStrRev(vFile, "\") + 1)
s = Left$(s, InStrRev(s, ".") - 1)
mycell.Value = s
Set wbCopyFrom = Workbooks.Open(vFile)
Set wsCopyFrom = wbCopyFrom.Worksheets(1)
'Copy Range
wsCopyFrom.Range("A1:N3000").Copy
wsCopyTo.Range("B2").PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
SendKeys "Y"
SendKeys ("{ESC}")
'Close file that was opened
wbCopyFrom.Close SaveChanges:=False
Application.Wait (Now + 0.000005)
Call NoSelect
Exit Sub
End Sub
Related
Been trying to figure out how to copy a cell from worksheet A and paste it down a column in Worksheet B until it matches the same amount of rows as an adjacent column. Take the following screenshot for example. How would I properly accomplish this in VBA? Been trying to figure this out for a while now. All I've been able to do is copy the cell and paste it adjacent to the last cell in the adjacent column instead of down the entire column. The worksheet I'm copying data from is pictured below.
Copy From SpreadSheet down below
Paste to SpreadSheet down below
Current Code
Sub pullSecEquipment()
Dim path As String
Dim ThisWB As String
Dim wbDest As Workbook
Dim shtDest As Worksheet
Dim shtPull As Worksheet
Dim Filename As String
Dim Wkb As Workbook
Dim CopyRng As Range, DestRng As Range
Dim lRow As Integer
Dim destLRow As Integer
Dim Lastrow As Long
Dim FirstRow As Long
Dim UpdateDate As String
ThisWB = ActiveWorkbook.Name
Dim selectedFolder
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
selectedFolder = .SelectedItems(1) & "\"
End With
path = selectedFolder
Application.EnableEvents = False
Application.ScreenUpdating = False
Set shtDest = Workbooks("GPnewchapterTEST2.xlsm").Worksheets("START")
'clear content of destination table
shtDest.Rows("8:" & Rows.Count).ClearContents
Filename = Dir(path & "\*.xls*", vbNormal)
If Len(Filename) = 0 Then Exit Sub
Do Until Filename = vbNullString
Set Wkb = Workbooks.Open(Filename:=path & "\" & Filename)
'MsgBox Filename
'''''
'SEC
'''''
If InStr(Filename, "Equipment") <> 0 Then
Dim range1 As Range
Set range1 = Range("E:K")
'For Each Wkb In Application.Workbooks
'For Each shtDest In Wkb.Worksheets
'Set shtPull = Wkb.Sheets(1)
'If shtPull.Name Like "*-*" Then
'last row
destLRow = Wkb.Sheets(1).Cells.Find(what:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row
'1st row
lRow = Wkb.Sheets(1).Cells.Find(what:="EQUIPMENT DESCRIPTION", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1
'STHours
Dim i As Integer
For i = lRow To destLRow
Set CopyRng = Wkb.Sheets(1).Range(Cells(i, 5).Address, Cells(i, 11).Address)
Set DestRng = shtDest.Range("O" & shtDest.Cells(Rows.Count, "O").End(xlUp).Row + 1)
CopyRng.Copy
DestRng.PasteSpecial Transpose:=True
Application.CutCopyMode = False 'Clear Clipboard
Set CopyRng = Wkb.Sheets(1).Range(Cells(i, 1).Address, Cells(i, 1).Address)
Set DestRng = shtDest.Range("C" & shtDest.Cells(Rows.Count, "O").End(xlDown).Row)
CopyRng.Copy
DestRng.PasteSpecial Transpose:=True
Application.CutCopyMode = False 'Clear Clipboard
Set CopyRng = Wkb.Sheets(1).Range(Cells(i, 3).Address, Cells(i, 3).Address)
Set DestRng = shtDest.Range("S" & shtDest.Cells(Rows.Count, "O").End(xlUp).Row)
CopyRng.Copy
DestRng.PasteSpecial Transpose:=True
Application.CutCopyMode = False 'Clear Clipboard
i = i + 2
Next i
'Dim cell As Integer
'Dim empname As String
'destLRow = 8 '' find out how to find first available row
'For cell = 2 To lRow
'empname = Wkb.Sheets(1).Cells(cell, 3).Value & " " & Wkb.Sheets(1).Cells(cell, 4).Value
' shtDest.Cells(8, 5).Value = empname
'shtDest.Cells(8, 1).Value = "Service Electric"
'Next cell
' Wkb.Close Save = False
End If
'End If
Filename = Dir()
Loop
MsgBox "Done!"
End Sub
if you want to do in VBA and want to copy one value in "ALL" column
Cells(1,1).Copy Columns(1)
Sorry that I am new to VBA, thanks to all the experts here I am able to copy some of the codes and modify them to suit my needs. Basically, they are just a couple of command buttons which carry out various functions. It work out fine in my excel 2010. However, when I try to save the file in my another computer with Excel 2007 (Confirmed that vba is running), a message popup saying
"The following Features cannot be saved in a macro-free workbooks:
VB Project
To save a file with these features, click no, and then choose a macro-enabled file type..."
Even I clicked no and then save it as xlsm. When I opened the file, all the vba codes are disabled. I just wonder whether it is due to any line of the following codes that could not be run in excel 2007. Many thanks for your help!
Apologies for the codes being a mess.
Private Sub CommandButton1_Click()
' Defines variables
Dim Wb1 As Workbook, Wb2 As Workbook
' Disables screen updating to reduce flicker
Application.ScreenUpdating = False
' Sets Wb1 as the current (destination) workbook
Set Wb1 = ThisWorkbook
' Sets Wb2 as the defined workbook and opens it - Update filepath / filename as required
Set Wb2 = Workbooks.Open("\\new_admin\MASTER_FILE.xlsx")
' Sets LastRow as the first blank row of Wb1 Sheet1 based on column A (requires at least header if document is otherwise blank)
lastrow = Sheets(1).Cells(Rows.count, "A").End(xlUp).Row + 1
' With workbook 2
With Wb2
' Activate it
.Activate
' Activate the desired sheet - Currently set to sheet 1, change the number accordingly
.Sheets(1).Activate
' Copy the used range of the active sheet
.ActiveSheet.UsedRange.Copy
End With
' Then with workbook 1
With Wb1.Sheets(1)
' Activate it
.Activate
' Select the first blank row based on column A
.Range("A1").Select
' Paste the copied data
.Paste
End With
' Close workbook 2
Wb2.Close
' Re-enables screen updating
Application.ScreenUpdating = False
End Sub
Private Sub CommandButton2_Click()
' Defines variables
Dim Wb1 As Workbook, Wb2 As Workbook
' Disables screen updating to reduce flicker
Application.ScreenUpdating = False
' Sets Wb1 as the current (destination) workbook
Set Wb1 = ThisWorkbook
' Sets Wb2 as the defined workbook and opens it - Update filepath / filename as required
Set Wb2 = Workbooks.Open("C:\Users\admin\Desktop\Accom_Master_File.xlsx")
' Sets LastRow as the first blank row of Wb1 Sheet1 based on column A (requires at least header if document is otherwise blank)
lastrow = Sheets(2).Cells(Rows.count, "A").End(xlUp).Row + 1
' With workbook 2
With Wb2
' Activate it
.Activate
' Activate the desired sheet - Currently set to sheet 1, change the number accordingly
.Sheets(1).Activate
' Copy the used range of the active sheet
.ActiveSheet.UsedRange.Copy
End With
' Then with workbook 1
With Wb1.Sheets(2)
' Activate it
.Activate
' Select the first blank row based on column A
.Range("A1").Select
' Paste the copied data
.Paste
End With
' Close workbook 2
Wb2.Close
' Re-enables screen updating
Application.ScreenUpdating = False
Dim wkb As Workbook
Set wkb = ThisWorkbook
wkb.Sheets("Sheet1").Activate
End Sub
Private Sub CommandButton3_Click()
Range("B2").CurrentRegion.Select
Selection.Sort Key1:=Range("B2"), Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
ThisWorkbook.Sheets("Sheet2").Range("B:C").Delete xlUp
ThisWorkbook.Sheets("Sheet2").Columns(2).Copy
ThisWorkbook.Sheets("Sheet2").Columns(1).Insert
ThisWorkbook.Sheets("Sheet2").Columns(3).Delete
End Sub
Private Sub CommandButton4_Click()
Dim dicKey As String
Dim dicValues As String
Dim dic
Dim data
Dim x(1 To 35000, 1 To 24)
Dim j As Long
Dim count As Long
Dim lastrow As Long
lastrow = Cells(Rows.count, 1).End(xlUp).Row
data = Range("A2:X" & lastrow) ' load data into variable
With CreateObject("scripting.dictionary")
For i = 1 To UBound(data)
If .Exists(data(i, 2)) = True Then 'test to see if the key exists
x(count, 3) = x(count, 3) & ";" & data(i, 3)
x(count, 8) = x(count, 8) & ";" & data(i, 8)
x(count, 9) = x(count, 9) & ";" & data(i, 9)
x(count, 10) = x(count, 10) & ";" & data(i, 10)
x(count, 21) = x(count, 21) & ";" & data(i, 21)
Else
count = count + 1
dicKey = data(i, 2) 'set the key
dicValues = data(i, 2) 'set the value for data to be stored
.Add dicKey, dicValues
For j = 1 To 24
x(count, j) = data(i, j)
Next j
End If
Next i
End With
Rows("2:300").EntireRow.Delete
Sheets("Sheet1").Cells(2, 1).Resize(count - 1, 24).Value = x
End Sub
Private Sub CommandButton5_Click()
If ActiveSheet.AutoFilterMode Then Selection.AutoFilter
ActiveCell.CurrentRegion.Select
With Selection
.AutoFilter
.AutoFilter Field:=1, Criteria1:="ACTIVE"
.AutoFilter Field:=5, Criteria1:="NUMBERS"
.Offset(1, 0).Select
End With
Dim ws As Worksheet
Dim rVis As Range
Application.ScreenUpdating = False
For Each ws In Worksheets
Do Until ws.Columns("A").SpecialCells(xlVisible).count = ws.Rows.count
Set rVis = ws.Columns("A").SpecialCells(xlVisible)
If rVis.Row = 1 Then
ws.Rows(rVis.Areas(1).Rows.count + 1 & ":" & rVis.Areas(2).Row - 1).Delete
Else
ws.Rows("1:" & rVis.Row - 1).Delete
End If
Loop
Next ws
Application.ScreenUpdating = True
Dim LR As Long
LR = Cells(Rows.count, 1).End(xlUp).Row
Rows(LR).Copy
Rows(LR + 2).Insert
End Sub
Private Sub CommandButton6_Click()
Columns("A").Delete
Dim lastrow As Long
lastrow = Range("A2").End(xlDown).Row
Range("X2:X" & lastrow).FormulaR1C1 = "=IF(RC[+1]=""PAYING"", VLOOKUP(RC[-23],'Sheet2'!R1C1:R20000C8,8,0),""PENDING"")"
Range("Y2:Y" & lastrow).FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-24],'Sheet2'!R1C1:R20000C8,2,0), ""PENDING"")"
Range("Z2:Z" & lastrow).FormulaR1C1 = "=(LEN(RC[-24])-LEN(SUBSTITUTE(RC[-24], "";"", """"))+1)*1200"
Range("AA2:AA" & lastrow).FormulaR1C1 = "=VLOOKUP(RC[-26],'Sheet3'!R2C2:R220C4,2,0)"
Range("AB2:AB" & lastrow).FormulaR1C1 = "=VLOOKUP(RC[-27],'Sheet3'!R2C2:R220C4,3,0)"
Range("AC2:AC" & lastrow).FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-28],'Sheet4'!R1C1:R30C3,2,0),"""")"
Range("AD2:AD" & lastrow).FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-29],'Sheet4'!R1C4:R30C6,2,0),"""")"
Columns("X:AD").EntireColumn.AutoFit
Sheets(1).Columns(24).NumberFormat = "#"
Sheets(1).Columns(25).NumberFormat = "#"
Sheets(1).Columns(29).NumberFormat = "#"
Sheets(1).Columns(30).NumberFormat = "#"
End Sub
Private Sub CommandButton7_Click()
Sheet1.Cells.Clear
End Sub
When something like this happens to me I just start up a new workbook and save explicitly in .xls or .xlsm format and then copy and paste my module or class code into new modules and classes in the new workbook. -- cannot post comments yet so if this doesn't help i shall delete this answer.
Hi I have a problem with a macro which copies information from one workbook and paste it into another. Then it creates two columns and fill them with an IF formula to compare two dates. Those formulas bring the wrong result as one of the columns have another date format, and I can't change it, whatever I do on the cell is not working, only if I erase the value on any cell of that column and write a date I can change the format.
The main format needed is YYYY-MM-DD, but this column is set as dd/mm/yyyy, even if I update the cell and set it as date or custom it doesn't work at all, it keeps showing the wrong format.
This is the macro I work on, is there any way to solve this issue?
Thank you in advance.
Sub AD_Audit()
'Last cell in column
Dim ws As Worksheet
Dim LastCell As Range
Dim LastCellRowNumber As Long
Dim wb3 As Workbook
Set ws = Worksheets(2)
With ws
Set LastCell = .Cells(.Rows.Count, "A").End(xlUp)
LastCellRowNumber = LastCell.Row + 1
End With
Dim Wb As Workbook, wb2 As Workbook
Dim vFile As Variant
'Set source workbook
Set Wb = ActiveWorkbook
'Open the target workbook
vFile = Application.GetOpenFilename("Excel-files,*.xlsx", _
1, "Select One File To Open", , False)
'if the user didn't select a file, exit sub
If TypeName(vFile) = "Boolean" Then Exit Sub
Workbooks.Open vFile
'Set selectedworkbook
Set wb2 = ActiveWorkbook
'Select cells to copy
wb2.Worksheets(2).Range("A1:BD" & ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row).Select
Selection.Copy
'Go back to original workbook you want to paste into
Wb.Activate
'Paste starting at the last empty row
Wb.Worksheets(2).Activate
Wb.Worksheets(2).Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Application.ScreenUpdating = True
Dim LstrDate As String
Dim LDate As Date
LstrDate = "Apr 6, 2003"
LDate = CDate(LstrDate)
'search for columns containing the data needed
Dim x As Integer
Dim lastRow As Long
lastRow = Cells.Find(What:="*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Dim rFind As Range
With Range("A:DB")
Set rFind = .Find(What:="Account Last Updated", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not rFind Is Nothing Then
End If
End With
Dim rFind1 As Range
With Range("A:DB")
Set rFind1 = .Find(What:="Termination Date", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not rFind1 Is Nothing Then
End If
End With
Dim rFind2 As Range
With Range("A:DB")
Set rFind2 = .Find(What:="Last Password set date", LookAt:=xlWhole, MatchCase:=False, SearchFormat:=False)
If Not rFind2 Is Nothing Then
End If
End With
'create columns and fill them with formulas
x = ActiveSheet.UsedRange.Columns.Count
ActiveSheet.Cells(1, x + 1) = "Account last updated after termination"
intcounter = 2
While (intcounter <= lastRow)
ActiveSheet.Cells(intcounter, x + 1).Formula = "=IF(TEXT(""" & Cells(intcounter, rFind.Column) & """,""YYYY/MM/DD"")>=TEXT(""" & Cells(intcounter, rFind1.Column) & """,""YYYY/MM/DD""),""review"",""disabled"")"
intcounter = intcounter + 1
Wend
x = ActiveSheet.UsedRange.Columns.Count
ActiveSheet.Cells(1, x + 1) = "Password After Termination"
intcounter = 2
While (intcounter <= lastRow)
ActiveSheet.Cells(intcounter, x + 1).Formula = "=IF(TEXT(""" & Cells(intcounter, rFind2.Column) & """,""YYYY/MM/DD"")>=TEXT(""" & Cells(intcounter, rFind1.Column) & """,""YYYY/MM/DD""),""review"",""old"")"
intcounter = intcounter + 1
Wend
'add column Actions
Worksheets(2).Range("A1").EntireColumn.Insert
Worksheets(2).Range("A1").Formula = "Actions"
'Set headers to bold text
Rows(1).Font.Bold = True
'check for filter, turn on if none exists
If Not ActiveSheet.AutoFilterMode Then
ActiveSheet.Range("A1:BD1").AutoFilter
End If
Dim Notes As Object, Maildb As Object, workspace As Object, UIdoc As Object, UserName As String
Dim MailDbName As String
ThisWorkbook.Activate
For Each Wb In Workbooks
If Not (Wb Is ActiveWorkbook) Then Wb.Close savechanges:=False
Next
End Sub
Date values are stored in a worksheet cell as a numerical value so different formats can be applied to different cells and still retain the ability to compare (or add, subtract, etc). The formula you're applied to each cell is forcing a comparison in a specific text format when the actual value.
The key is to set your formula up to use the address of the cell, not the cell contents.
So your cell formula can simply be:
ActiveSheet.Cells(intcounter, x + 1).Formula = "=If(" & Cells(intcounter, rFind.Column).Address & ">=" & Cells(intcounter, rFind1.Column).Address & ","""review""","""disabled""")"
I'm new to VBA and trying to automate updates to a workbook.
I have a source Workbook A and a destination Workbook B. Both have a sheet called roll out summary. I want the user to update this sheet in A and click update button which should run my macro. This macro should automatically update the sheet in workbook B without opening Workbook B.
I'm trying this code but it doesn't work and gives me an error:
Dim wkb1 As Workbook
Dim sht1 As Range
Dim wkb2 As Workbook
Dim sht2 As Range
Set wkb1 = ActiveWorkbook
Set wkb2 = Workbooks.Open("B.xlsx")
Set sht1 = wkb1.Worksheets("Roll Out Summary") <Getting error here>
Set sht2 = wkb2.Sheets("Roll Out Summary")
sht1.Cells.Select
Selection.Copy
Windows("B.xlsx").Activate
sht2.Cells.Select
Selection.PasteSpecial Paste:=xlPasteFormulasAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
sht1 and sht2 should be declare as Worksheet. As for updating the workbook without opening it, it can be done but a different approach will be needed. To make it look like you're not opening the workbook, you can turn ScreenUpdating on/off.
Try this:
Dim wkb1 As Workbook
Dim sht1 As Worksheet
Dim wkb2 As Workbook
Dim sht2 As Worksheet
Application.ScreenUpdating = False
Set wkb1 = ThisWorkbook
Set wkb2 = Workbooks.Open("B.xlsx")
Set sht1 = wkb1.Sheets("Roll Out Summary")
Set sht2 = wkb2.Sheets("Roll Out Summary")
sht1.Cells.Copy
sht2.Range("A1").PasteSpecial xlPasteValues
Application.CutCopyMode = False
wkb2.Close True
Application.ScreenUpdating = True
Use this - This worked for me
Sub GetData()
Dim lRow As Long
Dim lCol As Long
lRow = ThisWorkbook.Sheets("Master").Cells()(Rows.Count, 1).End(xlUp).Row
lCol = ThisWorkbook.Sheets("Master").Cells()(1, Columns.Count).End(xlToLeft).Column
If Sheets("Master").Cells(2, 1) <> "" Then
ThisWorkbook.Sheets("Master").Range("A2:X" & lRow).Clear
'Range(Cells(2, 1), Cells(lRow, lCol)).Select
'Selection.Clear
MsgBox "Creating Updated Master Data", vbSystemModal, "Information"
End If
'MsgBox ("No data Found")
'End Sub
cell_value = Sheets("Monthly Summary").Cells(1, 4)
If cell_value = "" Then
Filename = InputBox("No Such File Found,Enter File Path Manually", "Bad Request")
Else
MsgBox (cell_value)
Path = "D:\" & cell_value & "\"
Filename = Dir(Path & "*.xlsx")
If Filename = "" Then
Filename = InputBox("No Such File Found,Enter File Path Manually", "Bad Request")
Else
Do While Filename <> ""
On Error GoTo ErrHandler
Application.ScreenUpdating = False
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
ActiveWorkbook.Sheets("CCA Download").Activate
LastRow = ActiveSheet.Cells(Rows.Count, "D").End(xlUp).Row
Range("A2:X" & LastRow).Select
Selection.Copy
ThisWorkbook.Sheets("Master").Activate
LastRow = ActiveSheet.Cells(Rows.Count, "D").End(xlUp).Select
'Required after first paste to shift active cell down one
Do While Not IsEmpty(ActiveCell)
ActiveCell.Offset(1, 0).Select
Loop
ActiveCell.Offset(0, -3).Select
Selection.PasteSpecial xlPasteValues
Workbooks(Filename).Close
Filename = Dir()
Loop
End If
End If
Sheets("Monthly Summary").Activate
'Sheets("Monthly Summary").RefreshAll
Dim pvtTbl As PivotTable
For Each pvtTbl In ActiveSheet.PivotTables
pvtTbl.RefreshTable
Next
'Sheets("Monthly Sumaary").Refresh
MsgBox "Monthly MIS Created Sucessfully", vbOKCancel + vbDefaultButton1, "Sucessful"
ErrHandler:
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
I have a sheet(Questions) in a workbook(Rating) that has a button at the bottom of the Questions sheet that copies sheet 2(quote) from the Rating workbook and pastes it in a new workbook that is named according to the quote number and then saved.
Here is that code:
Sub GetQuote()
Range("AK548").Select
Selection.Copy
Range("AK549").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Dim Output As Workbook
Dim FileName As String
Set Output = Workbooks.Add
FileName = ThisWorkbook.Path & "\" & ThisWorkbook.Worksheets("Questions").Range("AK545").Value & ".xls"
Output.SaveAs FileName
Application.DisplayAlerts = False
Output.Worksheets("Sheet1").Delete
ThisWorkbook.Worksheets(2).Copy Before:=Output.Worksheets("Sheet2")
Output.Worksheets(1).Name = "Sheet1"
Application.DisplayAlerts = True
Output.Protect Password:="12345"
Output.Save
End Sub
Now I intend on removing the links that now exsist between this new copy and the Quote sheet and only leave the values. How would I do this?
I have found this code that should delete the links that exsist:
Dim Cell As Range, FirstAddress As String, Temp As String
'delete all links from selected cells
Application.ScreenUpdating = False
With Selection
Set Cell = .Find("=*!", LookIn:=xlFormulas, searchorder:=xlByRows, _
LookAt:=xlPart, MatchCase:=True)
On Error GoTo Finish
FirstAddress = Cell.Address
Do
Temp = Cell
Cell.ClearContents
Cell = Temp
Set Cell = .FindNext(Cell)
Loop Until Cell Is Nothing Or Cell.Address = FirstAddress
End With
Finish:
All I have done extra is put this code in below the code that Names and copies the sheet and that did not work?
So now how would I combine these two pieces of code so that everything gets copied and the links removed?
I had existing workbooks that had external links that i needed to remove from the workbooks and then re save them.
This worked for me:
Sub BreakExternalLinks()
'PURPOSE: Breaks all external links that would show up in Excel's "Edit Links" Dialog Box
'SOURCE: www.TheSpreadsheetGuru.com/The-Code-Vault
Dim ExternalLinksArray As Variant
Dim wb As Workbook
Dim x As Long
Set wb = ActiveWorkbook
'Create an Array of all External Links stored in Workbook
ExternalLinksArray = wb.LinkSources(Type:=xlLinkTypeExcelLinks)
'if the array is not empty the loop Through each External Link in ActiveWorkbook and Break it
If IsEmpty(ExternalLinksArray) = False then
For x = 1 To UBound(ExternalLinksArray )
wb.BreakLink Name:=ExternalLinksArray (x), Type:=xlLinkTypeExcelLinks
Next x
end if
End Sub
This piece of code kills all connections in the active workbook... apologies, but can't remember where I got it.
'Kill Connections
If ActiveWorkbook.Connections.Count > 0 Then
For i = 1 To ActiveWorkbook.Connections.Count
ActiveWorkbook.Connections.Item(1).Delete
Next i
Else
End If
Tested with your code, this seems to work:
Dim Output As Workbook
Dim FileName As String
Set Output = Workbooks.Add
FileName = ThisWorkbook.Path & "\" & ThisWorkbook.Worksheets("Questions").Range("A1").Value & ".xls"
Output.SaveAs FileName
Application.DisplayAlerts = False
Output.Worksheets("Sheet1").Delete
ThisWorkbook.Worksheets(2).Copy Before:=Output.Worksheets("Sheet2")
Output.Worksheets(1).Name = "Sheet1"
Output.Worksheets(1).Select
If ActiveWorkbook.Connections.Count > 0 Then
For i = 1 To ActiveWorkbook.Connections.Count
ActiveWorkbook.Connections.Item(1).Delete
Next i
Else
End If
Application.DisplayAlerts = True
Output.Protect Password:="12345"
Output.Save
Perhaps it would help, if you don't use the actual copy & paste functions. If you only need the values of the cells, then change your macro to
Sub GetQuote()
Range("AK548").Select
Selection.Copy
Range("AK549").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Dim Output As Workbook
Dim FileName As String
Set Output = Workbooks.Add
FileName = ThisWorkbook.Path & "\" & ThisWorkbook.Worksheets("Questions").Range("AK545").Value & ".xls"
Output.SaveAs FileName
Application.DisplayAlerts = False
Dim v, r As Long, c As Long
With ThisWorkbook.Worksheets(2)
r = .Cells.SpecialCells(xlCellTypeLastCell).Row
c = .Cells.SpecialCells(xlCellTypeLastCell).Column
v = .Range(.Cells(1, 1), .Cells(r, c))
End With
With Output.Worksheets(1)
.Range(.Cells(1, 1), .Cells(r, c)) = v
End With
Application.DisplayAlerts = True
Output.Protect Password:="12345"
Output.Save
End Sub
This copies the values of your origin sheet to the new workbook sheet, without any links.
P.S.: Don't mix up ThisWorkbook and ActiveWorkbook. ThisWorkbook is the workbook where the macro is located (, but not necessarily the active workbook). ActiveWorkbook is the workbook, you see at that time.