I will keep this quick. The attached code for the most part works i have used slight variations of it on other projects. the commented out range3.copy is from my last project.
I am currently having issues getting selection.copy to copy the selected range in the correct workbook. I have tried many things some are noted in the script. but I can not get the selection.copy to work
.range.copy will work and populate the clipboard. But I have not figured out how to pastespecial using .copy.
I tried outputting to variable .. didn't work as i thought it might. I feel I have to be missing something on the workbook selection/activation but I don't know what. Thanks in advance for any advice or assistance .. I will continue plugging away and see if I can figure it out.
Here is the first segment with the issue. SRCrange1.select then selection.copy does not actually copy the designated selection. The full code is below.
Dim MyColumn As String
Dim Here As String
Dim AC As Variant
'SRCrange1.copy ': This will copy to clipboard
'objworkbook.Worksheets("plan").Range("b6:h7").Select no change from SRCrange1.select
'SRCrange1.Select 'the range does select
'Selection.copy ' this will cause a activecell in DSTwb _
to be copied neither direct reference to SRCrange1.select or .avtivate will change that.
DSTwb.Select
DSTwb.Range("b2").Select
Here = ActiveCell.Address
MyColumn = Mid(Here, InStr(Here, "$") + 1, InStr(2, Here, "$") - 2)
Set lastrow = ActiveWorkbook.ActiveSheet.Range(MyColumn & "65536").End(xlUp).Offset(1, 0)
lastrow.Select
Selection.PasteSpecial Paste:=xlPasteValues, operation:=xlNone, skipblanks:=False, Transpose:=True
FULL CODE
Sub parse()
Dim strPath As String
Dim strPathused As String
'On Error Resume Next
Set objexcel = CreateObject("Excel.Application")
objexcel.Visible = True
objexcel.DisplayAlerts = False
strPath = "C:\prodplan"
Set objfso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objfso.GetFolder(strPath)
'Loop through objWorkBooks
For Each objfile In objFolder.Files
If objfso.GetExtensionName(objfile.Path) = "xlsx" Then
Set objworkbook = objexcel.Workbooks.Open(objfile.Path)
' Set path for move to at end of script
strPathused = "C:\prodplan\used\" & objworkbook.Name
'open WB to consolidate too
Workbooks.Open "C:\prodplan\compiled\plancon.xlsx"
'Range management sourcebook
Set SRCwb = objworkbook.Worksheets("plan")
Set SRCrange1 = objworkbook.Worksheets("plan").Range("b6:i7")
Set SRCrange2 = objworkbook.Worksheets("plan").Range("k6:p7")
'Set SRCrange3 = objworkbook.Worksheets("").Range("")
'Range management sourcebook
Set DSTwb = Workbooks("plancon.xlsx").Worksheets("data")
'Set DSTrange1 = Workbooks("plancon.xlsx").Worksheets("data").Range("")
'Set DSTrange2 = Workbooks("plancon.xlsx").Worksheets("data").Range("")
'Set DSTrange3 = Workbooks("plancon.xlsx").Worksheets("data").Range("")
'start header dates and shifts copy from objworkbook to consolidated WB
SRCwb.Select
'On Error Resume Next
'SRCwb.Cells.UnMerge
Dim MyColumn As String
Dim Here As String
Dim AC As Variant
'SRCrange1.copy ': This will copy to clipboard
'objworkbook.Worksheets("plan").Range("b6:h7").Select no change from SRCrange1.select
'SRCrange1.Select 'the range does select
'Selection.copy ' this will cause a activecell in DSTwb _
to be copied neither direct reference to SRCrange1.select or .avtivate will change that.
DSTwb.Select
DSTwb.Range("b2").Select
Here = ActiveCell.Address
MyColumn = Mid(Here, InStr(Here, "$") + 1, InStr(2, Here, "$") - 2)
Set lastrow = ActiveWorkbook.ActiveSheet.Range(MyColumn & "65536").End(xlUp).Offset(1, 0)
lastrow.Select
Selection.PasteSpecial Paste:=xlPasteValues, operation:=xlNone, skipblanks:=False, Transpose:=True
SRCrange2.Select
Selection.copy
Workbooks("plancon.xlsx").Worksheets("sheet1").Select
ActiveSheet.Range("b2").Select
ActiveSheet.Range("b2").Activate
Here = ActiveCell.Address
MyColumn = Mid(Here, InStr(Here, "$") + 1, InStr(2, Here, "$") - 2)
Set lastrow = ActiveWorkbook.ActiveSheet.Range(MyColumn & "65536").End(xlUp).Offset(1, 0)
lastrow.Select
Selection.PasteSpecial Paste:=xlPasteValues, operation:=xlNone, skipblanks:=False, Transpose:=True
' range3.copy
' Workbooks("data.xlsx").Worksheets("sheet1").Activate
' ActiveSheet.Range("c2").Select
' ActiveSheet.Range("c2").Activate
' Here = ActiveCell.Address
' MyColumn = Mid(Here, InStr(Here, "$") + 1, InStr(2, Here, "$") - 2)
' Set lastrow = ActiveWorkbook.ActiveSheet.Range(MyColumn & "65536").End(xlUp).Offset(1, 0)
' ActiveSheet.Paste Destination:=lastrow
'start loop for objworkbook name copy to field in plancon corisponding with date/shift and copy/paste select row data.
objworkbook.Close False
'Move proccesed file to new Dir
OldFilePath = objfile 'original file location
NewFilePath = strPathused ' new file location
Name OldFilePath As NewFilePath ' move the file
End If
Next
objexcel.Quit
End Sub
First, a relative welcome to SO!
Second, some tips for you that will make life easier in VBA programming:
Use Option Explicit and always Dimension and Declare your variable types.
When naming variables, make them easy to understand and follow. So, if you are going to create a worksheet variable, call it something like wksCopy. Or, if you are going to name a workbook, call it wkbCopyTo
You don't need to use .Select and .Activate, but rather you can work directly with your objects. Also, by declaring the appropriate variables types, this make it much easier to work with these objects in your code each time you need them.
I don't know if you are running this code inside Excel, or another application (like Access), but if you are in Excel, there is no need to create an Excel object, as you can work with the Excel App directly. Ignore this if you are using Access / Word / PPT etc to fire the code.
All these tips make your code much easier to read and understand and follow when trying to debug, and write.
All that said, I have refactored your code above to incorporate most of these principles (I kept all your variable names intact so you wouldn't get lost in any re-namings.) If this re-write doesn't directly solve your problem = which it may not, because the code is kind of confusing to me as written, I think it will be much easier for you to follow and understand and find out where it's not doing what you expect when you debug. Also, I think it will help us help you if you can't figure it out.
Sub parse()
Dim strPath As String, strPathused As String
Dim objexcel As Excel.Application
Set objexcel = CreateObject("Excel.Application")
With objexcel
.Visible = True
.DisplayAlerts = False
End With
strPath = "C:\prodplan"
Dim objfso As FileSystemObject, objFolder As Folder
Set objfso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objfso.GetFolder(strPath)
'Loop through objWorkBooks
For Each objfile In objFolder.Files
If objfso.GetExtensionName(objfile.Path) = "xlsx" Then
Dim objWorkbook As Excel.Workbook
Set objWorkbook = objexcel.Workbooks.Open(objfile.Path)
' Set path for move to at end of script
strPathused = "C:\prodplan\used\" & objWorkbook.Name
'open WB to consolidate too
objexcel.Workbooks.Open "C:\prodplan\compiled\plancon.xlsx"
'Range management sourcebook
Dim SRCwb As Excel.Worksheet, SRCrange1 As Excel.Range, SRCrange2 As Excel.Range
Set SRCwb = objWorkbook.Worksheets("plan") 'sjh -> to me wb implies wb, but you set it to a worksheet (could be a style thing, but worth pointing out
Set SRCrange1 = objWorkbook.Worksheets("plan").Range("b6:i7")
Set SRCrange2 = objWorkbook.Worksheets("plan").Range("k6:p7")
'Range management sourcebook
Set DSTwb = Excel.Worksheet
Set DSTwb = Workbooks("plancon.xlsx").Worksheets("data")
'start header dates and shifts copy from objworkbook to consolidated WB
Dim MyColumn As String
Dim Here As String
Dim AC As Variant
Here = DSTwb.Range("B2").Address
MyColumn = Mid(Here, InStr(Here, "$") + 1, InStr(2, Here, "$") - 2)
'sjh comment -> best to change "ActiveWorkbook" to the workbook referece you mean, like objWorkbook
Dim lastrow As Range
Set lastrow = ActiveWorkbook.ActiveSheet.Range(MyColumn & "65536").End(xlUp).Offset(1, 0)
SRCrange1.Copy
lastrow.PasteSpecial Paste:=xlPasteValues, operation:=xlNone, skipblanks:=False, Transpose:=True
Here = Workbooks("plancon.xlsx").Worksheets("sheet1").Range("B2").Address
MyColumn = Mid(Here, InStr(Here, "$") + 1, InStr(2, Here, "$") - 2)
'sjh comment -> best to change "ActiveWorkbook" to the workbook referece you mean, like objWorkbook
Set lastrow = ActiveWorkbook.ActiveSheet.Range(MyColumn & "65536").End(xlUp).Offset(1, 0)
SRCrange2.Copy
lastrow.PasteSpecial Paste:=xlPasteValues, operation:=xlNone, skipblanks:=False, Transpose:=True
objWorkbook.Close False
'Move proccesed file to new Dir
OldFilePath = objfile 'original file location
NewFilePath = strPathused ' new file location
Name OldFilePath As NewFilePath ' move the file
End If
Next
objexcel.Quit
End Sub
UPDATE If you are running this all in Excel. Just use this code below. I left both codes in my answer, in case you are not running this from Excel.
Option Explicit
Sub parse()
Application.DisplayAlerts = False
Dim strPath As String, strPathused As String
strPath = "C:\prodplan"
Dim objfso As FileSystemObject, objFolder As Folder
Set objfso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objfso.GetFolder(strPath)
'Loop through objWorkBooks
For Each objfile In objFolder.Files
If objfso.GetExtensionName(objfile.Path) = "xlsx" Then
Dim objWorkbook As Workbook
Set objWorkbook = Workbooks.Open(objfile.Path)
' Set path for move to at end of script
strPathused = "C:\prodplan\used\" & objWorkbook.Name
'open WB to consolidate too
Workbooks.Open "C:\prodplan\compiled\plancon.xlsx"
'Range management sourcebook
Dim SRCwb As Worksheet, SRCrange1 As Range, SRCrange2 As Range
Set SRCwb = objWorkbook.Worksheets("plan")
Set SRCrange1 = SRCwb.Range("b6:i7")
Set SRCrange2 = SRCwb.Range("k6:p7")
'Range management sourcebook
Dim DSTwb As Worksheet
Set DSTwb = Workbooks("plancon.xlsx").Worksheets("data")
'start header dates and shifts copy from objworkbook to consolidated WB
Dim MyColumn As String
Dim Here As String
Dim AC As Variant
Here = DSTwb.Range("B2").Address
MyColumn = Mid(Here, InStr(Here, "$") + 1, InStr(2, Here, "$") - 2)
'sjh comment -> best to change "ActiveWorkbook" to the workbook referece you mean, like objWorkbook or the other workbook you have open
Dim lastrow As Range
Set lastrow = ActiveWorkbook.ActiveSheet.Range(MyColumn & "65536").End(xlUp).Offset(1, 0)
SRCrange1.Copy
lastrow.PasteSpecial Paste:=xlPasteValues, operation:=xlNone, skipblanks:=False, Transpose:=True
Here = Workbooks("plancon.xlsx").Worksheets("sheet1").Range("B2").Address
MyColumn = Mid(Here, InStr(Here, "$") + 1, InStr(2, Here, "$") - 2)
'sjh comment -> best to change "ActiveWorkbook" to the workbook referece you mean, like objWorkbook or the other workbook you have open
Set lastrow = ActiveWorkbook.ActiveSheet.Range(MyColumn & "65536").End(xlUp).Offset(1, 0)
SRCrange2.Copy
lastrow.PasteSpecial Paste:=xlPasteValues, operation:=xlNone, skipblanks:=False, Transpose:=True
objWorkbook.Close False
'Move proccesed file to new Dir
OldFilePath = objfile 'original file location
NewFilePath = strPathused ' new file location
Name OldFilePath As NewFilePath ' move the file
End If
Next
End Sub
Just to add to the other answers: for contiguous ranges you don't need to use copy for this operation (pastespecial >> values + transpose)
Sub CopyValuesTranspose()
Dim rngCopy As Range, rngPaste As Range
Set rngCopy = Range("A1:B10")
Set rngPaste = Range("D1")
rngPaste.Resize(rngCopy.Columns.Count, rngCopy.Rows.Count).Value = _
Application.Transpose(rngCopy.Value)
End Sub
no need to select a range and then copy the selection, when you can copy a range directly:
objworkbook.Worksheets("plan").Range("b6:h7").Copy
same_or_different_Range.PasteSpecial Paste:=xlPasteValues, _
operation:=xlNone, skipblanks:=False, Transpose:=True
Related
I have a code which will read file data from the defined path and copies the data to my Macro workbook's sheet. When I am running the code line by line, it is working perfectly fine. But when I run the entire code, it is getting closed automatically without my permission. Below is my previous code.
Set thisWB = ThisWorkbook
'Open File and Copy Data
Set thatWB1 = Workbooks.Open(TimFilePath)
TFPLR = Cells(Rows.Count, "A").End(xlUp).Row
TFPLC = Cells(1, Columns.Count).End(xlToLeft).Column
TFPLCLTR = Split(Cells(1, TFPLC).Address(True, False), "$")(0)
'MsgBox TFPLCLTR
Range("A2:" & TFPLCLTR & TFPLR).Select
Selection.Copy
'Paste Selected Data in Time Ranges Sheet
'thisWB.Activate
thisWB.Sheets(TimSheet).Activate
If ActiveSheet.AutoFilterMode Then
ActiveSheet.AutoFilterMode = False
End If
Range("A2").PasteSpecial xlPasteValues
Application.CutCopyMode = False
'Close the File
thatWB1.Close SaveChanges:=False
After I made the below updates, the workbook is still closing.
Set thisWB = ThisWorkbook
'Open Time Range File and Copy Data
Set thatWB1 = Workbooks.Open(TimFilePath)
TFPLR = Cells(Rows.Count, "A").End(xlUp).Row
TFPLC = Cells(1, Columns.Count).End(xlToLeft).Column
TFPLCLTR = Split(Cells(1, TFPLC).Address(True, False), "$")(0)
'MsgBox TFPLCLTR
Range("A2:" & TFPLCLTR & TFPLR).Copy
'Selection.Copy
'Paste Selected Data in Time Ranges Sheet
thisWB.Sheets(TimSheet).Activate
If ActiveSheet.AutoFilterMode Then
ActiveSheet.AutoFilterMode = False
End If
thisWB.Sheets(TimSheet).Range("A2").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone _
, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
'Close the Time ranges File
thatWB1.Close SaveChanges:=False
Best way to solve this is by declaring a variable to fully control the open workbook in the same way you have for thisWB, eg:
Dim thatWB As Workbook
Set thatWB = Workbooks.Open(TimFilePath)
'do the work
thatWB.Close SaveChanges:=False
This code should work without relying on Active anything.
Option Explicit 'This line is REALLY important.
'It forces you to declare each variable.
'Tools ~ Options ~ Editor. Tick 'Require Variable Declaration' to
'add it to each new module you create.
Public Sub Test()
'Set references to required files.
Dim TimFilePath As String
TimFilePath = "C:/Somepath/MyFile.xlsx"
Dim thatWB As Workbook
Set thatWB = Workbooks.Open(TimFilePath)
Dim thatWS As Worksheet
Set thatWS = thatWB.Worksheets("Sheet1")
Dim thisWB As Workbook
Set thisWB = ThisWorkbook 'Workbook containing this code.
Dim thisWS As Worksheet
Set thisWS = thisWB.Worksheets("Sheet1")
'Work on the files without selecting them.
Dim LastRow As Long
LastRow = thatWS.Cells.Find("*", , , , xlByRows, xlPrevious).Row
If LastRow = 0 Then LastRow = 1
Dim LastColumn As Long
LastColumn = thatWS.Cells.Find("*", , , , xlByColumns, xlPrevious).Column
If LastColumn = 0 Then LastColumn = 1
Dim LastCell As Range
Set LastCell = thatWS.Cells(LastRow, LastColumn)
thatWS.Range("A2", LastCell).Copy
thisWS.Range("A2").PasteSpecial xlPasteValues
thatWB.Close False
End Sub
I am struggling with my VBA code. Instead of fixed values in a table, which contains the names how the workbooks should be saved as. My range needs to be variable (below example for starting with range "A3").
Sheets("CC").Select 'sheet with the names
Range("A3").Select ' starting from this range are the names in a column
Selection.Copy
Sheets("CZK").Select 'going to different sheet to paste some value
Range("B2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False 'pasting values to different sheet
Application.CutCopyMode = False
Sheets("CC").Select 'returning back to the sheet with names
Nazev = Range("A3")
ActiveWorkbook.SaveAs Filename:=cesta & Nazev 'saving it with predefined path and name
I have to start like this:
Set MyRange = Sheets("CC").Range("A3") ' predefining varible range
Set MyRange = Range(MyRange, MyRange.End(xlDown))
But then I am stuck.
Something like this should work for you:
Sub tst()
Dim wb As Workbook
Dim wsNames As Worksheet
Dim wsDest As Worksheet
Dim NameCells As Range
Dim NameCell As Range
Dim cesta As String
Dim Nazev As String
cesta = "C:\Test\"
Set wb = ActiveWorkbook
Set wsNames = wb.Sheets("CC")
Set wsDest = wb.Sheets("CZK")
Set NameCells = wsNames.Range("A3", wsNames.Cells(wsNames.Rows.Count, "A").End(xlUp))
Application.DisplayAlerts = False
For Each NameCell In NameCells
Nazev = NameCell.Value
wsDest.Range("B2").Value = Nazev
wb.SaveAs cesta & Nazev & ".xlsm", xlOpenXMLWorkbookMacroEnabled
Next NameCell
Application.DisplayAlerts = True
End Sub
I am new to VBA.
Transposing data from columns in one Workbook to another as rows is throwing errors. Tried suggestions from Stack Overflow and elsewhere but no success.
Error Runtime Error 1004 -> PasteSpecial method of Range class failed
Code:
Sub Button1_Click()
Dim MyFile As String
Dim erow
Dim FilePath As String
FilePath = "C:\trial\"
MyFile = Dir(FilePath)
Do While Len(MyFile) > 0
If MyFile = "here.xlsm" Then
Exit Sub
End If
'Opening data.xls to pull data from one column with 2 values (E6 and E7)
Workbooks.Open (FilePath & MyFile), Editable:=True
Dim SourceRange As Range
Set SourceRange = ActiveSheet.Range("E6:E7")
SourceRange.Copy
ActiveWorkbook.Close SaveChanges:=True
'Back to calling file - here.xlsm and pasting both values in single row (for e.g. A2 and B2)
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Dim targetRange As Range
Set targetRange = ActiveSheet.Cells(erow, 1)
targetRange.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
MyFile = Dir
Loop
End Sub
It is because you cannot do both values only and transpose at the same time.
Try this:
Sub Button1_Click()
Dim MyFile As String
Dim erow
Dim FilePath As String
Dim swb As Workbook
Dim twb As Workbook
Set twb = ThisWorkbook
FilePath = "C:\trial\"
MyFile = Dir(FilePath)
Do While Len(MyFile) > 0
If MyFile = "here.xlsm" Then
Exit Sub
End If
'Change "Sheet1" below to the actual name of the sheet
erow = twb.Sheets("Sheet1").Cells(twb.Sheets("Sheet1").Rows.Count, 1).End(xlUp).Offset(1, 0).Row
'Opening data.xls to pull data from one column with 2 values (E6 and E7)
Set swb = Workbooks.Open(FilePath & MyFile)
'assign values
twb.Sheets("Sheet1").Cells(erow, 1).Resize(, 2).Value = Application.Transpose(swb.ActiveSheet.Range("E6:E7").Value)
'close
swb.Close SaveChanges:=True
MyFile = Dir
Loop
End Sub
This seems to work:
Its a simpler example that does same thing
copy/paste method applies only to active objects (like, sheets, ranges, etc)
so you need to activate one, then the other,
Sub tst1()
Dim inbook, outbook As Workbook
Dim inSheet, outSheet As Worksheet
Dim inRange, outRange As Range
Set inbook = Application.Workbooks("temp1.xlsx")
Set outbook = Application.Workbooks("temp2.xlsx")
Set inSheet = inbook.Worksheets("sheet1")
Set outSheet = outbook.Worksheets("sheet1")
inSheet.Activate
Set inRange = ActiveSheet.Range("a1:b4")
inRange.Copy
outSheet.Activate
Set outRange = ActiveSheet.Range("a1:d2")
outRange.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
End Sub
While writing a piece of code I encountered the "Subscript out of range" message.
The structure of the folder is the following:
D:\Documents main directory
Inside it there are:
the xls workbook with the code
a file 1.csv to which I need to copy data
a folder WiP which contains csv files with the data
The code currently looks like this
Sub MergeData()
'
' Ìàêðîñ1 Ìàêðîñ
' Provide path to workbooks,
' there is a folder with about 100 csv books from which I should collect data into one
Dim Filename, Pathname As String
Dim wb As Workbook
Pathname = ActiveWorkbook.Path & "\WiP\"
Filename = Dir(Pathname & "*.csv")
' Open a workbook in which the data should be pasted
Workbooks.Open ("D:\Documents\1.csv")
ActiveSheet.Cells(1, 1).Value = "date"
ActiveSheet.Cells(1, 2).Value = "hour"
ActiveSheet.Cells(1, 3).Value = "num"
ActiveSheet.Cells(1, 4).Value = "p"
' Call the code
Do While Filename <> ""
Set wb = Workbooks.Open(Pathname & Filename)
IntegrateDays wb
wb.Close savechanges:=False
Filename = Dir()
Loop
' Close the workbook with data
Workbooks("D:\Documents\1.csv").Close savechanges:=True
End Sub
Sub IntegrateDays(wb As Workbook)
Dim ws As Worksheet
With wb
' Open workbooks, copy a range
Sheets(1).Activate
Dim rng As Range
Set rng = Range(Cells(1, 1), Cells(1, 1).End(xlDown))
rng.Copy
' Paste the range into 1.csv
Workbooks("D:\Documents\1.csv").Worksheets(1).Range("B" & Worksheets(1).UsedRange.Rows.Count + 1).Activate
rng.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Set NextRow = Nothing
End With
End Sub
The code runs until it has to paste the copied range rng into 1.csv and stops with an error.
The first guess is that this may be an error related to range.activate. I attempted to test it by doing the operation without loop and only selecting one cell and further by just opening 1.csv prior to even selecting any ranges. The error remains.
The second suspicion is that there is an issue opening 1.csv. By looking though searches such as "subscript out of range opening csv" I didn't find any heavily discussed issues which would help with this question.
Could you please kindly advise me what caused the error and how to rewrite the code?
Thank you very much in advance.
Evgeniya.
You shouldn't be using rng.PasteSpecial. The parent of the Range.PasteSpecial method should be the destination; not the source.
Since you are interested in getting the values over, abandon the PasteSpecial in favor of direct value transfer.
Dim rng As Range
with Sheets(1)
Set rng = .Range(Cells(1, 1), Cells(1, 1).End(xlDown))
end with
with Workbooks("D:\Documents\1.csv").Worksheets(1)
.cells(rows.count, "B").end(xlup).offset(1,0).resize(rng.rows.count, rng.columns.count) = rng.Value
end with
Are you trying to copy from a workbook into others?
Try adjust this
Application.ScreenUpdating = False
Columns("A:C").Sort Key1:=Range("C2"), _
Order1:=xlDescending, Header:=xlYes
Application.ScreenUpdating = True
Dim WBookCopy As Workbook
Dim WBookPst As Workbook
Dim Filepath As String
Dim SheetName As String
Dim sheetCopy As Worksheet
Set WBookPst = Application.ActiveWorkbook
Call DeleteCache
'B2 is the location directory of latest Excel file
Filepath = Range("B2").Value
Set WBookCopy = Workbooks.Open(Filepath)
Set sheetPst = WBookPst.Worksheets(2)
Set sheetCopy = WBookCopy.Worksheets(1)
sheetCopy.UsedRange.Copy sheetPst.Range("A:AG")
sheetCopy.UsedRange.Value = sheetCopy.UsedRange.Value
WBookCopy.Close (False)
I have been looking at this for to long so I am tossing it to those with more experience then I in hope of a copper or to of knowledge being tossed at me. The code runs with no errors.
The issue is that the second increment of the 1st loop overrides the first increments data range and so on. Loop 1 will populate rows 2:15. If I look at the address of lastrow it will show me the correct range of b16 as lastrow/cell in column to paste to , But as soon as the loop for the next objWorkBook runs it starts overwriting the fist increments cells rather then going to last row. I have a feeling i am missing something silly but it alludes me.
Any help or advice would be appreciated. I am relay interested in feed back. this will eventually process 100+ workbooks each adding roughly 1000 entries. I am concerned about the efficiency of my code. would using arrays speed things up? once things are caught up it will only process 2 workbooks a week. Again thank you for any pointer or advice your willing to share.
Option Explicit
Sub parse()
Application.DisplayAlerts = False
'Application.EnableCancelKey = xlDisabled
Dim strPath As String, strPathused As String
strPath = "C:\prodplan"
Dim objfso As FileSystemObject, objFolder As Folder, objfile As Object
Set objfso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objfso.GetFolder(strPath)
'Loop through objWorkBooks
For Each objfile In objFolder.Files
If objfso.GetExtensionName(objfile.Path) = "xlsx" Then
Dim objWorkbook As Workbook
Set objWorkbook = Workbooks.Open(objfile.Path)
' Set path for move to at end of script
strPathused = "C:\prodplan\used\" & objWorkbook.Name
'open WB to consolidate too
Workbooks.Open "C:\prodplan\compiled\plancon.xlsx"
'Range management WB
Dim SRCwb As Worksheet, SRCrange1 As Range, SRCrange2 As Range, lastrow As Range
Set SRCwb = objWorkbook.Worksheets("plan")
Set SRCrange1 = SRCwb.Range("b6:i7")
Set SRCrange2 = SRCwb.Range("k6:p7")
'Range management destination WB
Dim DSTws As Worksheet
Set DSTws = Workbooks("plancon.xlsx").Worksheets("data")
'start header dates and shifts copy from objworkbook to consolidated WB
Set lastrow = Workbooks("plancon.xlsx").Worksheets("data").Range("b" & ActiveSheet.Rows.Count).End(xlUp).Offset(1, 0)
SRCrange1.copy
lastrow.PasteSpecial Paste:=xlPasteValues, operation:=xlNone, skipblanks:=False, Transpose:=True
Range(ActiveCell, Selection.End(xlDown)).Offset(0, -1).Value = objWorkbook.Name
Set lastrow = Workbooks("plancon.xlsx").Worksheets("data").Range("b" & ActiveSheet.Rows.Count).End(xlUp).Offset(1, 0)
SRCrange2.copy
lastrow.PasteSpecial Paste:=xlPasteValues, operation:=xlNone, skipblanks:=False, Transpose:=True
Range(ActiveCell, Selection.End(xlDown)).Offset(0, -1).Value = objWorkbook.Name
'Begin loop to copy content.
Dim DSTheader As Range
Set DSTheader = DSTws.Range("d1:bw1")
Dim SRCheader As Range
Set SRCheader = SRCwb.Range("a1:a110")
Dim x As Variant
Dim y As Variant
Dim matchEXIT As Boolean
matchEXIT = False
For Each x In DSTheader
For Each y In SRCheader
Dim SRCrngCP1 As Range
Set SRCrngCP1 = SRCwb.Range(y.Offset(0, 1).Address & ":" & y.Offset(0, 8).Address)
Dim SRCrngCP2 As Range
Set SRCrngCP2 = SRCwb.Range(y.Offset(0, 10).Address & ":" & y.Offset(0, 15).Address)
If y > 0 Then
If x = y Then
Dim MyColumn As String
Dim Here As String
Here = DSTws.Range(x.Address).Address
MyColumn = Mid(Here, InStr(Here, "$") + 1, InStr(2, Here, "$") - 2)
Set lastrow = DSTws.Range(MyColumn & ActiveSheet.Rows.Count).End(xlUp).Offset(1, 0)
SRCrngCP1.copy
lastrow.PasteSpecial Paste:=xlPasteValues, operation:=xlNone, skipblanks:=False, Transpose:=True
Set lastrow = DSTws.Range(MyColumn & ActiveSheet.Rows.Count).End(xlUp).Offset(1, 0)
SRCrngCP2.copy
lastrow.PasteSpecial Paste:=xlPasteValues, operation:=xlNone, skipblanks:=False, Transpose:=True
If x = y Then matchEXIT = True
If matchEXIT = True Then Exit For
End If
End If
Next y
matchEXIT = False
Next x
MsgBox x
objWorkbook.Close False
'Move proccesed file to new Dir
Dim OldFilePath As String
Dim NewFilePath As String
OldFilePath = objfile 'original file location
NewFilePath = strPathused ' new file location
Name OldFilePath As NewFilePath ' move the file
End If
Set lastrow = Workbooks("plancon.xlsx").Worksheets("data").Range("b" & ActiveSheet.Rows.Count).End(xlUp).Offset(1, 0)
Next
End Sub
UNTESTED
Can you test this and tell me if you get any errors.
Option Explicit
Sub parse()
Dim MyColumn As String, Here As String, OldFilePath As String, NewFilePath As String
Dim strPath As String, strPathused As String
Dim objfso As FileSystemObject, objFolder As Folder, objfile As Object
Dim objWorkbook As Workbook, wbPlan As Workbook
Dim SRCwb As Worksheet, DSTws As Worksheet
Dim lastrow As Long, lastrowN As Long
Dim SRCrange1 As Range, SRCrange2 As Range
Dim DSTheader As Range, SRCheader As Range, x As Range, y As Range
Dim SRCrngCP1 As Range, SRCrngCP2 As Range
Application.DisplayAlerts = False
strPath = "C:\prodplan"
Set objfso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objfso.GetFolder(strPath)
'Loop through objWorkBooks
For Each objfile In objFolder.Files
If objfso.GetExtensionName(objfile.Path) = "xlsx" Then
Set objWorkbook = Workbooks.Open(objfile.Path)
Set SRCwb = objWorkbook.Worksheets("plan")
Set SRCrange1 = SRCwb.Range("B6:I7")
Set SRCrange2 = SRCwb.Range("K6:P7")
' Set path for move to at end of script
strPathused = "C:\prodplan\used\" & objWorkbook.Name
'open WB to consolidate too
Set wbPlan = Workbooks.Open("C:\prodplan\compiled\plancon.xlsx")
Set DSTws = wbPlan.Worksheets("data")
lastrow = DSTws.Range("B" & DSTws.Rows.Count).End(xlUp).Row + 1
With DSTws.Range("B" & lastrow)
SRCrange1.Copy
.PasteSpecial Paste:=xlPasteValues, operation:=xlNone, skipblanks:=False, Transpose:=True
lastrowN = DSTws.Range("B" & DSTws.Rows.Count).End(xlUp).Row
.Range("A" & lastrow & ":A" & lastrowN).Value = objWorkbook.Name
lastrow = lastrowN + 1
SRCrange2.Copy
.PasteSpecial Paste:=xlPasteValues, operation:=xlNone, skipblanks:=False, Transpose:=True
lastrowN = DSTws.Range("B" & DSTws.Rows.Count).End(xlUp).Row
.Range("A" & lastrow & ":A" & lastrowN).Value = objWorkbook.Name
End With
Set DSTheader = DSTws.Range("D1:BW1")
Set SRCheader = SRCwb.Range("A1:A110")
For Each x In DSTheader
For Each y In SRCheader
Set SRCrngCP1 = SRCwb.Range(y.Offset(0, 1).Address & ":" & y.Offset(0, 8).Address)
Set SRCrngCP2 = SRCwb.Range(y.Offset(0, 10).Address & ":" & y.Offset(0, 15).Address)
If y > 0 Then
If x = y Then
Here = x.Address
MyColumn = Mid(Here, InStr(Here, "$") + 1, InStr(2, Here, "$") - 2)
lastrow = DSTws.Range(MyColumn & DSTws.Rows.Count).End(xlUp).Row + 1
With DSTws.Range("B" & lastrow)
SRCrngCP1.Copy
.PasteSpecial Paste:=xlPasteValues, operation:=xlNone, skipblanks:=False, Transpose:=True
lastrow = DSTws.Range(MyColumn & DSTws.Rows.Count).End(xlUp).Row + 1
SRCrngCP2.Copy
.PasteSpecial Paste:=xlPasteValues, operation:=xlNone, skipblanks:=False, Transpose:=True
End With
If x = y Then Exit For
End If
End If
Next y
Next x
objWorkbook.Close False
OldFilePath = objfile 'original file location
NewFilePath = strPathused ' new file location
Name OldFilePath As NewFilePath ' move the file
End If
Next
End Sub
Ok so i figured it out after a nice long weekend away from it. With a Duh moment had
'open WB to consolidate too
Workbooks.Open "C:\prodplan\compiled\plancon.xlsx"
Inside the loop that was suppose to copy to it so at each loop it reset my copy to WB causing what looked like overwriting.
I moved the open line out and the loop increments the paste to last cell with no issue. it did however break
Range(ActiveCell, Selection.End(xlDown)).Offset(0, -1).Value = objWorkbook.Name
Well sort of .. If I f8 down the code it works .. if I run the code it skips the line .. I dunno... .I will re post with another Question if I can't figure it out.