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.
Related
First, I begin with having a Master File. The Master File has names of 40 other workbooks.
I need to write a VBA code that works on this 40 workbooks (names defined in A1-A40 in the masterfile). This code should go to each workbook, open it, and copy the data in the first sheet of each workbook.
Thereafter, it will go back to the Master workbook and paste special in separate new sheets. For example, workbookA1's data goes into Sheet1 and workbookA2's data goes into Sheet2. However, I am having some trouble with it. The error says "PasteSpecial Method of Range Class" failed.
Sub Macro2()
Dim thiswb As Workbook, datawb As Workbook
Dim datafolder As String
Dim cell As Range, datawblist As Range
Dim i As Integer
Set thiswb = ActiveWorkbook
i = 2
'Have the 40 file names in sheet2 of this workbook in cells A1:A40
Set datawblist = Sheets("command").Range("A1:A4")
datafolder = "C:\Users\bryan\Desktop\Y4S1\Money and Banking\Empirical\QuarterSheets\2012q1\" 'change this to your directory they're in
For Each cell In datawblist
Workbooks.Open Filename:=datafolder & cell & ".csv", ReadOnly:=True
Set datawb = ActiveWorkbook
Sheets(1).Select 'change this to the sheet name you need to copy from
Range("A1:XFD1048576").Select
Do Until ActiveCell.Value = ""
Selection.Copy
ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)
thiswb.Activate
ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)
Selection.PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, _
SkipBlanks:=False, _
Transpose:=True
ActiveCell.Offset(0, 4).Select
datawb.Activate
ActiveCell.Offset(0, 1).Select
Loop
datawb.Close savechanges:=False
thiswb.Activate
Sheets("command").Select
i = i + 1
Cells(i, 1).Select
Next
End Sub
Try this, which removes the Selects and Activates, and restricts the copied range to the used range rather than every single cell. I think I've interpreted your scenario correctly, but shout if not.
Sub Macro2()
Dim thiswb As Workbook, datawb As Workbook, ws As Worksheet
Dim datafolder As String
Dim cell As Range, datawblist As Range
Dim i As Long
Set thiswb = ThisWorkbook
i = 2
'Have the 40 file names in sheet2 of this workbook in cells A1:A40
Set datawblist = thiswb.Sheets("command").Range("A1:A4")
datafolder = "C:\Users\bryan\Desktop\Y4S1\Money and Banking\Empirical\QuarterSheets\2012q1\" 'change this to your directory they're in
For Each cell In datawblist
Set datawb = Workbooks.Open(Filename:=datafolder & cell & ".csv", ReadOnly:=True)
Set ws = thiswb.Sheets.Add(After:=thiswb.Worksheets(Worksheets.Count))
datawb.Sheets(1).UsedRange.Copy
ws.Range("A1").PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, _
SkipBlanks:=False, _
Transpose:=True
datawb.Close savechanges:=False
Next
End Sub
I have two workbooks, source workbook and a Destination workbook.
I would like to copy particular column (A,C;D;E;F;G;K;AP;AV;AW;AX)containing data from source workbook to the Destination workbook in column (A till E). I already searched through the page and could find a code like below
Sub Extract()
Dim x As Workbook
Dim y As Workbook
Dim Value As Variant
Set y = ThisWorkbook
Set x = Workbooks.Open("D:\data\Jenny_Work.xlsx")
Value = x.Sheets("Work_Jenny").Range("A1").Value
y.Sheets("Sheet1").Range("A1").Value = Value
x.Close
End Sub
It would be great if you can suggest me for the above criteria
Thanking in advance
try this
it is working for me!
Sub Extract()
Dim x As Workbook
Dim y As Workbook
Dim Value As Variant
Set y = ThisWorkbook
Set x = Workbooks.Open("G:\Book1.xlsm")
lRow = x.Worksheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
dRow = y.Worksheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
Union(y.Worksheets("Sheet1").Range("A1:A" & dRow), y.Worksheets("Sheet1").Range("B1:B" & dRow)).Copy
x.Worksheets("Sheet1").Range("A" & lRow).PasteSpecial xlPasteAll
Application.CutCopyMode = False
x.Save
End Sub
Please note that a sheet is not the same as a workbook as this will create confusion.
A workbook/excel file can contain multiple sheets/worksheets and not the other way around.
That being said here is your code:
Sub RunMe()
Dim lRow, lCol As Integer
Sheets("Master").Select
lRow = Range("A" & Rows.Count).End(xlUp).Row
lCol = Cells(1, Columns.Count).End(xlToLeft).Column
For Each cell In Range(Cells(1, "B"), Cells(1, lCol))
Union(Range("A1:A" & lRow), Range(Cells(1, cell.Column), Cells(lRow, cell.Column))).Copy
Workbooks.Add
Range("A1").PasteSpecial
ActiveWorkbook.SaveAs Filename:= _
"C:\YourMap\" & cell.Value & ".xls" 'You might want to change the extension (.xls) according to your excel version
ActiveWorkbook.Close
Next cell
Application.CutCopyMode = False
End Sub
Just watch the file extension within the code (look for green text after pasting.).
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
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
See picture: http://s12.postimg.org/ov8djtuh9/Capture.jpg
Context: Trying to activate a sheet (variable: cSheet) in another workbook and paste data there from copied data from a different workbook. I'm getting a subscript out of range error whenever I try to activate directly using the variable (i.e. Worksheets(Name).Activate) or try to define a worksheet using the variable and then activate it. I've also tried other coding styles, using "With Worksheet" etc. and my code was a lot longer but I started over because every time I fix something, something else goes wrong. So, sticking to the basics. Any help would be greatly appreciated.
Sub GenSumRep()
Dim AutoSR As Workbook
Dim asrSheet As Worksheet
Dim tempWB As Workbook
Dim dataWB As Workbook
Dim SecName As String
Dim oldcell As String
Dim nsName As String
Dim cSheet As Worksheet
Set AutoSR = ActiveWorkbook
Set asrSheet = AutoSR.ActiveSheet
For a = 3 To 10
SecName = asrSheet.Range("D" & a).Value
If SecName <> "" Then
Workbooks.Open Range("B" & a).Value
Set tempWB = ActiveWorkbook
'tempWB.Windows(1).Visible = False
AutoSR.Activate
Workbooks.Open Range("C" & a).Value
Set dataWB = ActiveWorkbook
'dataWB.Windows(1).Visible = False
AutoSR.Activate
'Copy paste data
For b = 24 To 29
oldcell = Range("C" & b).Value
If b = 24 Then
nsName = Trim(SecName) & " Data"
Set cSheet = tempWB.Sheets(nsName)
Else
nsName = asrSheet.Range("B" & b).Value
Set cSheet = tempWB.Sheets(nsName)
End If
'Copy
dataWB.Activate
Range(oldcell).Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
'Paste
tempWB.Activate
cSheet.Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
b = b + 1
Next b
End If
a = a + 1
Next a
End Sub
You only get that error for one reason: the name your provided does not exist in the collection!
There are a couple of likely reasons for this based on your code:
Your nsName variable contains hidden characters that make it different even though it appears correct.
You are looking for the sheet in the wrong workbook.
Based on your comments, it seems that you are looking in the wrong workbook. A good way to check out these subscript errors is to iterate the collection and print out the Names included therein.
Dim sht as Worksheet
For Each sht In tempWB.Sheets
Debug.Print sht.Name
Next sht
In general, it is desirable to get rid of calls to Select and Activate so that you are not relying on the interface in order to get objects. See this post about avoiding Select and Activate for more info.
One idea applied to your code is to assign the Workbooks directly without ActiveWorkbook:
Set tempWB = Workbooks.Open(asrSheet.Range("B" & a).Value)
Set dataWB = Workbooks.Open(asrSheet.Range("C" & a).Value)
instead of:
Workbooks.Open Range("B" & a).Value
Set tempWB = ActiveWorkbook
'tempWB.Windows(1).Visible = False
AutoSR.Activate
Workbooks.Open Range("C" & a).Value
Set dataWB = ActiveWorkbook
'dataWB.Windows(1).Visible = False