excel cell = filename of another workbook - vba

I have a macro for updating a sheet from another workbook, how can I use that same file to update a cell with its filename without the .xlsx.
Can I use the vFile or wbCopyFrom Dim?
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
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
On Error GoTo whoa
'Open file with data to be copied
vFile = "C:\Users\taylorm1\Desktop\OUC\_Materials\Stock Status\Transmission Stock Status*.xlsx"
'vFile = "P:\ESO\1790-ORL\OUC\_Materials\Stock Status\Transmission Stock Status **-**-**.xlsx"
Set wbCopyFrom = Workbooks.Open(vFile)
Set wsCopyFrom = wbCopyFrom.Worksheets(1)
'Copy Range
wsCopyFrom.Range("A1:N3000").Copy
'wsCopyFrom.Range("A1:A" & LastRow).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
Application.ScreenUpdating = True
whoa:
vFile = Application.GetOpenFilename("Excel Files (*.xl*)," & _
"*.xl*", 1, "Select Excel File", "Open", False)
Set wbCopyFrom = Workbooks.Open(vFile)
Set wsCopyFrom = wbCopyFrom.Worksheets(1)
'Copy Range
wsCopyFrom.Range("A1:N3000").Copy
'wsCopyFrom.Range("A1:A" & LastRow).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
'whoa: 'If filename changes then open folder
'Call Shell("explorer.exe" & " " & "P:\ESO\1790-ORL\OUC\_Materials\Stock Status", vbNormalFocus)
End Sub
Thanks

You can get the file's name without path and without extension like this:
Dim s As String
s = Mid(vFile, InStrRev(vFile, "\") + 1)
s = Left$(s, InStrRev(s, ".") - 1)
Or if you want to keep the full path but only remove the extension:
Dim s As String
s = Left(vFile, InStrRev(vFile, ".") - 1)
Then assign it to any cell: myCell.Value = s

Try this code.
Private Sub TestNettFileName()
Debug.Print NettFileName(ThisWorkbook.Name)
End Sub
Private Function NettFileName(Fn As String) As String
Dim Sp() As String
Sp = Split(ActiveWorkbook.Name, ".")
ReDim Preserve Sp(UBound(Sp) - 1)
NettFileName = Join(Sp, ".")
End Function
Use it in your project like,
With ActiveSheet
.Range("A3").Value = NettFileName(.Parent.Name)
End With

Related

Allow user to select csv's VBA not working

I would like to modify the following code so that two things happen:
1) The user is able to select the csv's they want in a folder
2)Keep the header for the first csv only and keep the body for the rest of Csvs
How would I go about this in the following code? I keep receiving an error currently when I run this code.
Sub ImportCSVsWithReference()
Dim xSht As Worksheet
Dim xWb As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
On Error GoTo ErrHandler
Set xFileDialog = Application.FileDialog(msoFileDialogFilePicker)
xFileDialog.AllowMultiSelect = True
xFileDialog.Title = "Select a folder [CSV Consolidation]"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
Set xSht = ThisWorkbook.ActiveSheet
If MsgBox("Clear the existing sheet before importing?", vbYesNo) = vbYes Then xSht.UsedRange.Clear
Application.ScreenUpdating = False
xFile = Dir(xStrPath & "\" & "*.csv")
Do While xFile <> ""
Set xWb = Workbooks.Open(xStrPath & "\" & xFile)
Columns(1).Insert xlShiftToRight
Columns(1).SpecialCells(xlBlanks).Value = ActiveSheet.Name
ActiveSheet.UsedRange.Copy xSht.Range("A" & Rows.Count).End(xlUp).Offset(1)
xWb.Close False
xFile = Dir
Loop
Application.ScreenUpdating = True
Range("A1:R1").Select
Selection.AutoFilter
Range("L1").AutoFilter Field:=12, Criteria1:="<>"
Selection.End(xlToLeft).Select
Range("A1").CurrentRegion.Select
Selection.Copy
Sheets.Add
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Exit Sub
ErrHandler:
MsgBox "no files csv", , "Team"
End Sub
Here is a little starter for you.
It grab files without your error and then you can do what you want.
Sub ImportCSVsWithReference()
Dim xSht As Worksheet
Dim xWb As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
Set xFileDialog = Application.FileDialog(msoFileDialogFilePicker)
xFileDialog.AllowMultiSelect = True
xFileDialog.Title = "Select a folder [CSV Consolidation]"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
Set xSht = ThisWorkbook.ActiveSheet
If MsgBox("Clear the existing sheet before importing?", vbYesNo) = vbYes Then xSht.UsedRange.Clear
Application.ScreenUpdating = False
Dim vrtSelectedItem As Variant
Set xWb = Workbooks.Open(xStrPath)
MsgBox "Opened " & xStrPath & " for headers"
'Do your work with headers here with xWb as workbook with code
xWb.Close False
For Each vrtSelectedItem In xFileDialog.SelectedItems
Set xWb = Workbooks.Open(vrtSelectedItem)
MsgBox "Opened " & vrtSelectedItem & " for content"
'Do your work with content here with xWb as workbook with code
xWb.Close False
Next
Application.ScreenUpdating = True
End Sub

Error On Second Iteration: Application-defined or object-defined error

This year I inherited support of about a dozen accdb applications in Office 2010 Win 7 that often manipulate external excel files.
I keep getting the same error scenario. It is in my vba for excel commands,
but only AFTER the first iteration of a loop. It always works fine the first time through. Seems to have something to do with how I am identifying the objects. I've read multiple articles on best practices for working with the objects and the specific error but nothing has translated into a solution. Can someone ELI5 what I am doing wrong?
In the example below it is throwing the error early in the second iteration at the Range("A1").Select command.
Code:
Sub runCleanAndImportUnpre()
Dim strFolder As String
Dim strTableDest As String
strTableDest = "Unpresented_EOD_Import"
strFolder = "C:\Users\lclambe\Projects\Inputs\test2"
Call CleanAndImportUnpresentedInAGivenFolder(strTableDest, strFolder)
End Sub
Function CleanAndImportUnpresentedInAGivenFolder(strTable As String, strFolder As String)
' Function that opens files in a folder, cleans them up and saves them.
Dim myfile
Dim mypath
Dim strPathFileName As String
Dim i As Integer
'Call ClearData(strTable)
'if it needs a backslash on the end, add one
If Right(strFolder, 1) <> "\" Then
strFolder = strFolder & "\"
End If
mypath = strFolder
ChDir (strFolder)
myfile = Dir(mypath)
ChDir (mypath)
myfile = Dir("")
i = 1
Do While myfile <> ""
'Format the excel report
strPathFileName = mypath & myfile
'use for unpresented
Call formatExcelUnPresentedForImport(strPathFileName)
i = i + 1
myfile = Dir()
Loop
End Function
Function formatExcelUnPresentedForImport(filePath As String)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Note:
' Called from CleanAndImportUnpresentedInAGivenFolder when
' importing Unpresented reports
'
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
On Error GoTo formatExcelUnPresentedForImport_Error
Dim strFilePath As String
Dim strReportType As String
Dim i As Integer
Dim iTotal_Row
Dim Lastrow As Long
Dim iCol As Integer
Dim appExcel As excel.Application
Dim wkb As excel.Workbook
Dim sht As Worksheet
Dim rng As Range
strReportType = reportType
strFilePath = filePath
Set appExcel = New excel.Application
appExcel.Visible = False
'Define the worksheet
Set wkb = appExcel.Workbooks.Open(strFilePath, ReadOnly:=False)
'Turn off error msg: "minor loss of fidelity" if you are sure no data will be lost
wkb.CheckCompatibility = False
'Expand Column to avoid scientific notation
appExcel.Columns("A:A").EntireColumn.AutoFit
'Find last row
'FAILS HERE ON SECOND ITERATION OF LOOP:
Range("A1").Select
ActiveCell("A1").Select
Selection.End(xlDown).Select
'Delete the last 3 rows of totals
ActiveCell.offset(-2, 0).Select
Selection.EntireRow.Delete
Selection.EntireRow.Delete
Selection.EntireRow.Delete
'Add a TRIM of Cash Amount Field2 at column L
Range("L2").Select
ActiveCell.FormulaR1C1 = "=TRIM(RC[-9])"
Range("L2").Select
'Copy it to rest of cells to bottom
Selection.Copy
Lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
Selection.AutoFill Destination:=Range("L2:L" & Lastrow), Type:=xlFillDefault
Range("L2:L" & Lastrow).Select
'Delete original unformatted unpresented
Selection.Copy
ActiveSheet.Paste
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'Delete all the rows except Unpresented
Range("B:B,C:C,D:D,E:E,F:F,G:G,H:H,I:I,J:J,K:K").Select
Range("K1").Activate
Selection.Delete Shift:=xlToLeft
'Add a Header
Range("B1").Select
ActiveCell.FormulaR1C1 = "Unpresented"
wkb.Save
wkb.Close
appExcel.Quit
Set wkb = Nothing
Set appExcel = Nothing
On Error GoTo 0
Exit Function
formatExcelUnPresentedForImport_Error:
Set wkb = Nothing
Set appExcel = Nothing
strMessage = "Error " & err.Number & " (" & err.Description & ") in procedure formatExcelUnPresentedForImport of Module modExternalExcelClean."
strMessage = strMessage & " Application will stop processing now." & vbNewLine
strMessage = strMessage & "Please note or copy this error message and contact application developer for assistance."
MsgBox strMessage, vbCritical + vbOKOnly, "Error"
End
End Function
Just guessing that you are not iterating through an Excel file the second time, thus it throws an error. To debug it in ELI5 style, change your code like this:
Do While myfile <> ""
MsgBox myFile
'Format the excel report
strPathFileName = mypath & myfile
'use for unpresented
Call formatExcelUnPresentedForImport(strPathFileName)
i = i + 1
myfile = Dir()
Loop
and pay attention to the MsgBox every time. Is it showing what you think it should be showing?

Issue flattening Excel Files to a new folder using VBA

I currently have the following code. Currently this code will loop through a folder of excel files and will open them and then save them in that folder, but I can't get the code to then take those files flatten them and then place them into another folder. Any advice?
Sub ALoopFile()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.PrintCommunication = False
Dim MyFolder As String
Dim MyFile As String
Dim SendTo As String
Dim SendFile As String
Dim CurrentWB As Workbook 'Workbook Stores Workbook
MyFolder = "Y:\Dropbox (Efficiency3)\Monthly Projects\001 - AU"
MyFile = Dir(MyFolder & "\*.xls")
SendTo = "Y:\Dropbox (Efficiency3)\Monthly Projects\001 - AU\Flattened_Files"
SendFile = Dir(SendTo & "\*.xls")
Do While MyFile <> ""
Set CurrentWB = Workbooks.Open(Filename:=MyFolder & "\" & MyFile, UpdateLinks:=3) 'Sets CurrentWB = to that long name. This becomes the name of the workbook.
CurrentWB.RunAutoMacros Which:=xlAutoOpen 'Enables Macros in Workbook
CurrentWB.SaveAs Filename:=MyFolder & "\" & MyFile, FileFormat:=56
For SheetNumber = 1 To CurrentWB.Sheets.Count 'Counts Worksheets in Workbook
CurrentWB.Sheets(SheetNumber).Select 'Selects All Worksheets in Workbook
If (CurrentWB.Sheets(SheetNumber).Name <> "What If") Then
CurrentWB.Sheets(SheetNumber).Unprotect ("UMC626") 'Unprotects Workbook
Cells.Select 'Selects Data in Workbook
With CurrentWB.Sheets(SheetNumber).UsedRange
.Value = .Value
End With
CurrentWB.Sheets(SheetNumber).Protect Password:="UMC626", DrawingObjects:=True, Contents:=True, Scenarios:=True 'Protects Workbook
End If
Next SheetNumber 'Runs Through Iteration
Sheets(1).Select
Range("A1").Select 'Saves each workbook at the top of the page
CurrentWB.SaveAs Filename:=SendTo & "\" & SendFile, FileFormat:=56, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False 'Saves Workbook in Flatten File Location
CurrentWB.Close 'Closes Workbook
MyFile = Dir
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.PrintCommunication = True
End Sub
I solved the issue by using ThisName = CurrentWB.Name
ALoopFile()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.PrintCommunication = False
Dim MyFolder As String
Dim MyFile As String
Dim SendTo As String
Dim SendFile As String
Dim CurrentWB As Workbook 'Workbook Stores Workbook
MyFolder = "Y:\Dropbox (Efficiency3)\Monthly Projects\001 - AU\"
MyFile = Dir(MyFolder & "\*.xls")
SendTo = "Y:\Dropbox (Efficiency3)\Monthly Projects\001 - AU\Flattened_Files"
SendFile = Dir(SendTo & "\*.xls")
Do While MyFile <> ""
Set CurrentWB = Workbooks.Open(Filename:=MyFolder & "\" & MyFile, UpdateLinks:=3) 'Sets CurrentWB = to that long name. This becomes the name of the workbook.
CurrentWB.RunAutoMacros Which:=xlAutoOpen 'Enables Macros in Workbook
CurrentWB.SaveAs Filename:=MyFolder & "\" & MyFile, FileFormat:=56
ThisName = CurrentWB.Name
For SheetNumber = 1 To CurrentWB.Sheets.Count 'Counts Worksheets in Workbook
CurrentWB.Sheets(SheetNumber).Select 'Selects All Worksheets in Workbook
If (CurrentWB.Sheets(SheetNumber).Name <> "What If") Then
CurrentWB.Sheets(SheetNumber).Unprotect ("UMC626") 'Unprotects Workbook
Cells.Select 'Selects Data in Workbook
With CurrentWB.Sheets(SheetNumber).UsedRange
.Value = .Value
End With
CurrentWB.Sheets(SheetNumber).Protect Password:="UMC626", DrawingObjects:=True, Contents:=True, Scenarios:=True 'Protects Workbook
End If
Next SheetNumber 'Runs Through Iteration
Sheets(1).Select
Range("A1").Select 'Saves each workbook at the top of the page
CurrentWB.SaveAs Filename:=SendTo & "\" & ThisName
CurrentWB.Close 'Closes Workbook
MyFile = Dir
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.PrintCommunication = True
End Sub

error handler works only once in vba

I am trying to pull data from several workbooks which have different sheet names. I have created an array which contains all the possible sheet names. When data workbook opens and sheet name is not found the error handler works for the first time when loop runs again and pull the next array element, error handler doesn't work. It gives "Subscript out of range" error. Can anyone please elaborate what am I missing here? What I want is in case consecutive sheet names are not available in data workbook, code should go into for loop again and search for next sheet name.
Public strFileName As String
Public currentWB As Workbook
Public dataWB As Workbook
Sub GetData()
Dim strListSheet As String
Dim i As Integer
Dim VendorValue As String
Dim SheetNames() As Variant
Dim a As String
strListSheet = "Master"
Sheets(strListSheet).Select
Range("First_file").Select
SheetNames = Range("Sheet_Names")
'this is the main loop, we will open the files one by one and copy their data into the masterdata sheet
Set currentWB = ActiveWorkbook
Do While ActiveCell.Value <> ""
strFileName = ActiveCell.Offset(0, 1) & ActiveCell.Value
VendorValue = ActiveCell.Offset(0, 2)
Application.Workbooks.Open strFileName, UpdateLinks:=False, ReadOnly:=True
Set dataWB = ActiveWorkbook
For i = LBound(SheetNames, 1) To UBound(SheetNames, 1)
a = SheetNames(i, 1)
b = SheetNames(i, 2)
dataWB.Activate
On Error GoTo Handler:
ActiveWorkbook.Sheets(a).Select
Range("H5:H120,I5:I120,M5:M120,P5:P120,U5:X120").Select
Selection.Copy
currentWB.Activate
Sheets(VendorValue).Select
Range(b).Select
Selection.PasteSpecial xlPasteValues, xlPasteSpecialOperationNone
Application.CutCopyMode = False
Handler:
Next
dataWB.Close False
Sheets(strListSheet).Select
ActiveCell.Offset(1, 0).Select
Loop
Exit Sub
End Sub
You have to exit the error handler in order to reuse it. That is you need a Resume clause at the end of your error handler.
Check this site for more details.
I have moved the handler at the end of the sub and added a Resume.
Public strFileName As String
Public currentWB As Workbook
Public dataWB As Workbook
Sub GetData()
Dim strListSheet As String
Dim i As Integer
Dim VendorValue As String
Dim SheetNames() As Variant
Dim a As String
strListSheet = "Master"
Sheets(strListSheet).Select
Range("First_file").Select
SheetNames = Range("Sheet_Names")
'this is the main loop, we will open the files one by one and copy their data into the masterdata sheet
Set currentWB = ActiveWorkbook
Do While ActiveCell.Value <> ""
strFileName = ActiveCell.Offset(0, 1) & ActiveCell.Value
VendorValue = ActiveCell.Offset(0, 2)
Application.Workbooks.Open strFileName, UpdateLinks:=False, ReadOnly:=True
Set dataWB = ActiveWorkbook
For i = LBound(SheetNames, 1) To UBound(SheetNames, 1)
a = SheetNames(i, 1)
b = SheetNames(i, 2)
dataWB.Activate
On Error GoTo Handler:
ActiveWorkbook.Sheets(a).Select
Range("H5:H120,I5:I120,M5:M120,P5:P120,U5:X120").Select
Selection.Copy
currentWB.Activate
Sheets(VendorValue).Select
Range(b).Select
Selection.PasteSpecial xlPasteValues, xlPasteSpecialOperationNone
Application.CutCopyMode = False
Handler2:
Next
dataWB.Close False
Sheets(strListSheet).Select
ActiveCell.Offset(1, 0).Select
Loop
Exit Sub
Handler:
Resume Handler2
End Sub
I'd change approach like follows:
Dim mySht as Worksheet
a = SheetNames(i, 1)
Set mySht = GetSheet(dataWB, a)
If Not mySht Is Nothing Then
b = SheetNames(i, 2)
With mySht
.Range("H5:H120,I5:I120,M5:M120,P5:P120,U5:X120").Copy
currentWB.Sheets(VendorValue).Range(b).PasteSpecial xlPasteValues, xlPasteSpecialOperationNone
Application.CutCopyMode = False
End With
End If
Where I only showed the part that goes from a and b settings (included) to the Handler label (included, i.e. it has to disappear).
And you have to put this code in any module (also at the end of your Sub will do):
Function GetSheet(wb as Workbook, shtName as String)
On Error Resume Next
Set GetSheet = wb.Worksheet(shtName)
End Function
Finally the rest of your code can avoid a lot of Activate/Active/Select/Selection stuff in a similar manner
If all your files are in the same path, I think it's easier to use this:
Sub openOtherWorkbooks()
Dim folderPath As String, path As String
folderPath = "C:\Path\to\your\files"
path = folderPath & "\*.xlsm" 'xlsm as an example - could be xls* as well
Do While Filename <> ""
Filename = Dir()
If Filename <> ThisWorkbook.Name And Filename <> "" Then
Workbooks.Open folderPath & "\" & Filename
For i = 1 To Workbooks(Filename).Sheets.count
' do everything with every sheet of this file
Next i
Workbooks(Filename).Close False
End If
Filename = Dir(path)
Loop
End Sub
It's just opening every file, counting the sheets (beginning with 1) of the opened file and then there should be your code.
It's not exactly an answer to your On-Error-GoTo-thing with your handler.

Copy data from multiple files into one sheet with incremental rows.

I'm using the following code to open one of multiple files, copy a line from a worksheet, and then paste it back into the first worksheet, then close the opened file.
My problem is I can't get past the function to move down the rows each time it pastes. I want it to incrementally paste the values on the new row, ie. B3, then B4, then B5, etc.
Sub Auto_open_change()
Dim WrkBook As Workbook
Dim StrFileName As String
Dim FileLocnStr As String
Dim LAARNmeWrkbk As String
PERNmeWrkbk = ThisWorkbook.Name
FileLocnStr = "T:\Projects\data" 'ThisWorkbook.Path
Dim StrFile As String
StrFile = Dir(FileLocnStr & "\*.xls")
Do While Len(StrFile) > 0
DoStuff (FileLocnStr & "\" & StrFile)
StrFile = Dir
Loop
End Sub
Private Sub DoStuff(StrFileName)
Workbooks.Open (StrFileName)
Call Edit
Workbooks.Open (StrFileName)
ActiveWorkbook.Close
End Sub
Sub Edit()
Dim Wb1 As Workbook
Dim ws1 As Worksheet
Dim loopcal As Long
With Application
.ScreenUpdating = False
.EnableEvents = False
lngCalc = .Calculation
End With
Set Wb1 = ActiveWorkbook
Sheets("1_3 Octave1 CH1").Select
Range("A3:AH3").Select
Selection.Copy
Windows("template.xlsm").Activate
Sheets("Data Extract").Select
Range("B3").Select
Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End Sub
You can try this:
Sub GetData(Fname as String)
Dim wb1, wb2 as Workbook
Dim ws1, ws2 as Worksheet
Dim lrow as Long
Set wb1 = Thisworkbook
Set ws1 = wb1.Sheets("DataExtract")
Set wb2 = Worbooks.Open(Fname)
Set ws2 = wb2.Sheets("1_3 Octave1 CH1")
With ws1
lrow = .Range("B" & Rows.Count).End(xlUp).Row
ws2.Range("A3:AH3").Copy
.Range("B" & lrow).Offset(1,0).PasteSpecial xlPasteValues
Application.CutCopyMode = False
End With
wb2.Close False
End Sub
Just replace DoStuff and Edit subs.
hope this helps.
Untested:
Sub Auto_open_change()
Dim StrFileName As String
Dim FileLocnStr As String
Dim fNum As Long
Dim StrFile As String
FileLocnStr = "T:\Projects\data" 'ThisWorkbook.Path
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
fNum = 1
StrFile = Dir(FileLocnStr & "\*.xls")
Do While Len(StrFile) > 0
CopyData FileLocnStr & "\" & StrFile, fNum
StrFile = Dir
fNum = fNum + 1
Loop
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
Sub CopyData(StrFileName As String, fNum As Long)
Dim Wb1 As Workbook, rngCopy As Range
Dim rngDest As Range
Set Wb1 = Workbooks.Open(StrFileName)
Set rngCopy = Wb1.Sheets("1_3 Octave1 CH1").Range("A3:AH3")
Set rngDest = ThisWorkbook.Sheets("Data Extract") _
.Range("B2").Offset(fNum, 0)
rngCopy.Copy rngDest
With rngDest.Resize(rngCopy.Rows.Count, rngCopy.Columns.Count)
.Value = .Value
End With
Wb1.Close False
End Sub
Well, with the code you're using, you could just create a variable in the Do While Loop that calls DoStuff and pass it through to the Edit sub, then construct the range from that.
So in the Do While Loop
rowcounter = 3
Do While Len(StrFile) > 0
DoStuff (FileLocnStr & "\" & StrFile, rowcounter)
StrFile = Dir
rowcounter = rowcounter + 1
Loop
Then modify DoStuff
Private Sub DoStuff(StrFileName As String, rowcounter As Integer)
Workbooks.Open (StrFileName)
Call Edit(rowcounter)
Workbooks.Open (StrFileName)
ActiveWorkbook.Close
End Sub
Then modify Edit
Sub Edit(rowcounter As Integer)
.
.
.
.
Windows("template.xlsm").Activate
Sheets("Data Extract").Select
Range("B" & rowcounter).Select
.
.
End Sub
'Guys, here is the final edit. works perfectly, Thanks for the help and support guys.
Option Explicit
Sub Auto_open_change()
Dim WrkBook As Workbook
Dim StrFileName As String
Dim FileLocnStr As String
Dim LAARNmeWrkbk As String
Dim rowcounter As Integer
FileLocnStr = "T:\Projects\data" 'ThisWorkbook.Path
Dim StrFile As String
StrFile = Dir(FileLocnStr & "\*.xls")
rowcounter = 3
Do While Len(StrFile) > 0
Call DoStuff(FileLocnStr & "\" & StrFile, rowcounter)
StrFile = Dir
rowcounter = rowcounter + 1
Loop
End Sub
Private Sub DoStuff(StrFileName As String, rowcounter As Integer)
Workbooks.Open (StrFileName)
Call Edit(rowcounter)
Workbooks.Open (StrFileName)
ActiveWorkbook.Close
End Sub
Sub Edit(rowcounter As Integer)
Dim Wb1 As Workbook
Dim ws1 As Worksheet
Dim loopcal As Long
With Application
.ScreenUpdating = True
.EnableEvents = True
lngCalc = .Calculation
End With
Set Wb1 = ActiveWorkbook
Sheets("1_3 Octave1 CH1").Select
Range("A3:AH3").Select
Selection.Copy
Windows("template.xlsm").Activate
Sheets("Data Extract").Select
Range("B" & rowcounter).Select
'index the variable to ensure the cell reference changes each time.
Selection.PasteSpecial Paste:=xlPasteAllUsingSourceTheme, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End Sub