Find loop not working correctly - loops

I am trying to design a vba macro script for Mac Office 2011 that uses find in column A to find a filename previously selected by the user.
The user selects a .csv file, then macro looks through column A to find filename without .csv extension. Once found, it offsets by one column (to column B) and imports the csv information.
What I currently have is not doing the find and then select? I can't seem to figure out what I am doing wrong here.
The csv will import, but just next to the cell I had active before running macro. This is why I think the Find is not working.
Any help would be most appreciated.
Sub CSVauto()
'
' CSVauto Macro
'
' Keyboard Shortcut: Option+Cmd+x
'
' Declaring and setting variables for choosing CSV to import
Dim csvFileName As Variant
''Prompt window to choose csv file
csvFileName = Application.GetOpenFilename(FileFilter:="")
If csvFileName = False Then Exit Sub
'Setting a variable to find Experimental form name in Data Summary
Dim whatToFind As String 'Declaring that variable
If Right(csvFileName, 4) = ".csv" Then
whatToFind = Replace(csvFileName, ".csv", "")
Else
MsgBox "Selected File Not .csv)"
End If
'Looping through A column to find csvFileName without .csv extension
Set cell = Range("A:A").Find(What:=whatToFind, LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False)
If Not cell Is Nothing Then
cell.Select
End If
'Speeding macro up by making it work in background
Sheets("DataSummary").DisplayPageBreaks = False
Application.DisplayAlerts = False
Dim MyRange As Range
Set MyRange = ActiveCell.Offset(0, 1)
MyRange.Select
'xlOverwriteCells
On Error Resume Next
'Formatting for CSV and input
With MyRange.Parent.QueryTables.Add(Connection:="TEXT;" & csvFileName, Destination:=MyRange)
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = False
.TextFilePromptOnRefresh = False
.TextFilePlatform = xlMacintosh
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = True
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = True
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.Refresh BackgroundQuery:=False
.UseListObject = False
End With
'Formatting DataSummary sheet to fit "requirements" :)
Cells.Replace What:=">=", Replacement:="", LookAt:=xlPart, SearchOrder:=xlByColumns, MatchCase:=False
Cells.Replace What:="C121", Replacement:="C2", LookAt:=xlPart, _
SearchOrder:=xlByColumns, MatchCase:=False
Cells.Replace What:="P1211", Replacement:="P21", LookAt:=xlPart, _
SearchOrder:=xlByColumns, MatchCase:=False
Cells.Select
With Selection
.HorizontalAlignment = xlLeft
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
End With
With Selection
.HorizontalAlignment = xlCenter
.Orientation = 0
.AddIndent = False
.ShrinkToFit = False
End With
Range("A4").Select
' Set Do loop to stop when an empty cell is reached.
Do Until IsEmpty(ActiveCell)
' Insert your code here.
' Step down 1 row from present location.
ActiveCell.Offset(1, 0).Select
Loop
'undoing everything working in background
Sheets("DataSummary").DisplayPageBreaks = True
Application.ScreenUpdating = True
End Sub

Take a look at where you "Set cell =...." you are having it look for whatToFind.
In your if/else statement above that, you never set whatToFind in the "else" statement. You need to set whatToFind as something in the else statement, if I am reading your request correctly.
It looks to me what you are asking for is to find a file that is NOT a .csv then to perform the function of searching/offset.
Please correct me if I am wrong or please clarify.
EDIT
This code should work for you. I tried it with your code with this inserted just below the if/else statement
Dim filename As Variant
filename = Mid(whatToFind, InStrRev(whatToFind, "/") + 1)
MsgBox filename

Related

Get data from excel to office word array using VBA

I have an excel file where are stored in columns some text and keywords.
I want to use the data in excel to make some Advanced search in Word using vba. But I'm getting an error trying to transpose the data from excel cells to an array in vba word.
I have used the transpose excel function but it doesn't handle more than 255 characters so I can't get cell's value that exceeds 255 characters.
I would be thankfull if someone could give me a hand.
Option Explicit
Dim strArray
Dim range As range
Dim i As Long
Dim numberOfUniqMatches As Integer
Dim totalMatches As Integer
Sub HighlightMatchesAndSummarize()
totalMatches = 0
'************************************ GET DATA FROM EXCEL ***************************************
Dim xlApp As Object
Dim xlBook As Object
Const strWorkBookName As String = "D:\keyword_source_3.xlsx"
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err Then
Set xlApp = CreateObject("Excel.Application")
End If
On Error GoTo 0
Set xlBook = xlApp.Workbooks.Open(FileName:=strWorkBookName)
'xlApp.Visible = True
xlApp.Visible = False
'transpose excel cells in our arrays
strArray = xlApp.Transpose(xlApp.ActiveSheet.range("A1:A20" & AlRow).Value)
Set xlBook = Nothing
xlApp.Quit
Set xlApp = Nothing
'
' End of data extraction
'/******************************** SEARCH LOOP START **********************************
For i = 1 To UBound(strArray)
numberOfUniqMatches = 0
Set range = ActiveDocument.range
With range.Find
.Text = strArray(i)
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchFuzzy = False
.MatchPhrase = True
.MatchSoundsLike = False
.MatchAllWordForms = False
Do While .Execute(Forward:=True) = True
numberOfUniqMatches = numberOfUniqMatches + 1
totalMatches = totalMatches + 1
range.HighlightColorIndex = wdYellow
Loop
End With
Next
'
' End of search loop
' Display message if no matching word is found
If totalMatches <= 0 Then
MsgBox "Sorry! No matching keyword found."
Else
MsgBox "Search ended: " & totalMatches & " matching word(s)."
End If
End Sub
Change this:
strArray = xlApp.Transpose(xlApp.ActiveSheet.range("A1:A20" & AlRow).Value)
To:
'remove the transpose (and fix the range...)
strArray = xlApp.ActiveSheet.range("A1:A" & AlRow).Value
Then in your loop:
For i = 1 To UBound(strArray, 1) '<<<<<<<
numberOfUniqMatches = 0
Set range = ActiveDocument.range
With range.Find
.Text = strArray(i, 1) '<<<<<<<
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchFuzzy = False
.MatchPhrase = True
.MatchSoundsLike = False
.MatchAllWordForms = False
Do While .Execute(Forward:=True) = True
numberOfUniqMatches = numberOfUniqMatches + 1
totalMatches = totalMatches + 1
range.HighlightColorIndex = wdYellow
Loop
End With
Next
Saerch for Byte in your code and replace it by Long. Ctrl+H is the shortcut for Replace.

Merging tables and arrays from multiple sheets into one consolidated table

I am very new to VBA and struggling!
I've tried searching the forums but can't find anything close enough to my situation...
I have 30+ sheets titled 001, 002 ...0nn
I want to create a new sheet title 'Actions summary'
I want this sheet to contain compiled information from each sheet with sheet name '0nn' (or i tried limiting the code to sheet names that are integers) - -
From each sheet i want to copy the information from columns A to G, And rows 9 to last row with information in.
I would also like the heading (A8:G8) at the top of the new 'actions summary' sheet.
SCREEN SHOT typical sheet 0nn format
Been going a bit mad and would really appreciate some simple help, ideally the code required with explanations for what each bit is doing so i can learn.
My Attempt below:
Function LastRow(sh As Worksheet)
On Error Resume Next
LastRow = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
End Function
Function LastCol(sh As Worksheet)
On Error Resume Next
LastCol = sh.Cells.Find(What:="*", _
After:=sh.Range("A1"), _
lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
On Error GoTo 0
End Function
Sub CopyRangeFromMultiWorksheets()
Dim sh As Worksheet
Dim DestSh As Worksheet
Dim Last As Long
Dim CopyRng As Range
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
' Delete the summary sheet if it exists.
Application.DisplayAlerts = False
On Error Resume Next
ActiveWorkbook.Worksheets("Actions Summary").Delete
On Error GoTo 0
Application.DisplayAlerts = True
' Add a new summary worksheet.
Set DestSh = ActiveWorkbook.Worksheets.Add
DestSh.Name = "Actions Summary"
' Loop through all worksheets and copy the data to the
' summary worksheet.
For Each sh In ActiveWorkbook.Worksheets
'If LCase(Left(sh.Name, 1)) = "0" Then
If IsNumeric(sh.Name) = True Then
Debug.Print (sh.Name)
' Find the last row with data on the summary worksheet.
Last = LastRow(DestSh)
'LastRow = Cells.SpecialCells(xlCellTypeLastCell).Row
Debug.Print (Last)
' Specify the range to place the data.
Set CopyRng = sh.Range("A9").CurrentRegion
Set CopyRng = Range(Cells(9, 1), Cells(Last, 7))
' Test to see whether there are enough rows in the summary
' worksheet to copy all the data.
If Last + CopyRng.Rows.Count > DestSh.Rows.Count Then
MsgBox "There are not enough rows in the " & _
"summary worksheet to place the data."
GoTo ExitTheSub
End If
' This statement copies values and formats from each
' worksheet.
CopyRng.Copy
With DestSh.Cells(Last + 1, "A")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End With
' Optional: This statement will copy the sheet
' name in the H column.
' DestSh.Cells(Last + 1, "H").Resize(CopyRng.Rows.Count).Value = sh.Name
End If
Next
'ExitTheSub:
Application.Goto DestSh.Cells(1)
' AutoFit the column width in the summary sheet.
DestSh.Columns.AutoFit
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
Sub selectA1_and_insertRow()
'
' selectA1_and_insertRow Macro
Worksheets("Actions Summary").Rows("1:1").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Columns("B:B").ColumnWidth = 36.43
Rows("1:1").Select
'Range.Copy to other worksheets
Worksheets("001").Range("A8:G8").Copy Worksheets("Actions Summary").Range("A1:G1")
End Sub
Many thanks in advance.
Tom
CODE:
Here's the new code:
Sub UpDate_List_v2()
Dim wb As Workbook
Dim ws As Worksheet
Dim wsSum As Worksheet
Dim rLastCell As Range
Dim lCalc As XlCalculation
Dim bHasHeaders As Boolean
'Turn off calculation, events, and screenupdating
'This allows the code to run faster and prevents "screen flickering"
With Application
lCalc = .Calculation
.Calculation = xlCalculationManual
.EnableEvents = False
.ScreenUpdating = False
End With
Set wb = ActiveWorkbook
'Check if Actions Summary sheet exists already or not
On Error Resume Next
Set wsSum = wb.Sheets("Actions summary")
On Error GoTo 0
If wsSum Is Nothing Then
'Does not exist, create it
Set wsSum = wb.Sheets.Add(Before:=wb.Sheets(1))
wsSum.Name = "Actions summary"
bHasHeaders = False
Else
'Already exists, clear previous data
wsSum.UsedRange.Offset(1).Clear
bHasHeaders = True
End If
'Loop through all sheets in the workbook
For Each ws In wb.Sheets
'Only look for worksheets whose names are numbers (e.g. "001", "002", etc)
If IsNumeric(ws.Name) Then
'Check if the "Actions Summary" sheet already has headers
If bHasHeaders = False Then
'Does not have headers yet
With ws.Range("A8:M8")
'Check if this sheet has headers in A8:G8
If WorksheetFunction.CountBlank(.Cells) = 0 Then
'This sheet does have headers, copy them over
.Copy wsSum.Range("A1")
bHasHeaders = True
End If
End With
End If
'Find the last row of the sheet
Set rLastCell = ws.Cells.Find("*", ws.Range("A1"), SearchDirection:=xlPrevious)
If Not rLastCell Is Nothing Then
'Check if the last row is greater than the header row
If rLastCell.Row > 8 Then
'Last row is greater than the header row so there is data
'Check if the "Actions Summary" sheet has enough rows to hold the data
If wsSum.Cells(wsSum.Rows.Count, "A").End(xlUp).Row + rLastCell.Row - 8 > wsSum.Rows.Count Then
'Not enough rows, return error and exit the subroutine
MsgBox "There are not enough rows in the summary worksheet to place the data.", , "Data Overflow"
Exit Sub
Else
'Does have enough rows, copy the data - Values
ws.Range("A9:M" & rLastCell.Row).Copy
With wsSum.Cells(wsSum.Rows.Count, "A").End(xlUp).Offset(1)
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
End If
End If
End If
End If
Next ws
'Sheets("Actions summary").Columns("H:L").EntireColumn.Delete 'Delete unwanted columns
'Sheets("Actions summary").Columns("H:L").Hidden = True 'Hide unwanted columns
Worksheets("Actions summary").Columns("H:j").Hidden = True
Worksheets("Actions summary").Columns("L").Hidden = True
Sheets("Actions summary").Columns("H").Style = "currency" 'Set to £
Application.CutCopyMode = False 'Remove the cut/copy border
'wsSum.Range("A1").CurrentRegion.EntireColumn.AutoFit 'Autofit columns on the "Actions Summary" sheet
'Turn calculation, events, and screenupdating back on
With Application
.Calculation = lCalc
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
Something like this should work for you. I have commented the code for clarity.
Sub tgr()
Dim wb As Workbook
Dim ws As Worksheet
Dim wsSum As Worksheet
Dim rLastCell As Range
Dim lCalc As XlCalculation
Dim bHasHeaders As Boolean
'Turn off calculation, events, and screenupdating
'This allows the code to run faster and prevents "screen flickering"
With Application
lCalc = .Calculation
.Calculation = xlCalculationManual
.EnableEvents = False
.ScreenUpdating = False
End With
Set wb = ActiveWorkbook
'Check if Actions Summary sheet exists already or not
On Error Resume Next
Set wsSum = wb.Sheets("Actions summary")
On Error GoTo 0
If wsSum Is Nothing Then
'Does not exist, create it
Set wsSum = wb.Sheets.Add(Before:=wb.Sheets(1))
wsSum.Name = "Actions summary"
bHasHeaders = False
Else
'Already exists, clear previous data
wsSum.UsedRange.Offset(1).Clear
bHasHeaders = True
End If
'Loop through all sheets in the workbook
For Each ws In wb.Sheets
'Only look for worksheets whose names are numbers (e.g. "001", "002", etc)
If IsNumeric(ws.Name) Then
'Check if the "Actions Summary" sheet already has headers
If bHasHeaders = False Then
'Does not have headers yet
With ws.Range("A8:G8")
'Check if this sheet has headers in A8:G8
If WorksheetFunction.CountBlank(.Cells) = 0 Then
'This sheet does have headers, copy them over
.Copy wsSum.Range("A1")
bHasHeaders = True
End If
End With
End If
'Find the last row of the sheet
Set rLastCell = ws.Cells.Find("*", ws.Range("A1"), SearchDirection:=xlPrevious)
If Not rLastCell Is Nothing Then
'Check if the last row is greater than the header row
If rLastCell.Row > 8 Then
'Last row is greater than the header row so there is data
'Check if the "Actions Summary" sheet has enough rows to hold the data
If wsSum.Cells(wsSum.Rows.Count, "A").End(xlUp).Row + rLastCell.Row - 8 > wsSum.Rows.Count Then
'Not enough rows, return error and exit the subroutine
MsgBox "There are not enough rows in the summary worksheet to place the data.", , "Data Overflow"
Exit Sub
Else
'Does have enough rows, copy the data - Values
ws.Range("A9:G" & rLastCell.Row).Copy
With wsSum.Cells(wsSum.Rows.Count, "A").End(xlUp).Offset(1)
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
End If
End If
End If
End If
Next ws
Application.CutCopyMode = False 'Remove the cut/copy border
wsSum.Range("A1").CurrentRegion.EntireColumn.AutoFit 'Autofit columns on the "Actions Summary" sheet
'Turn calculation, events, and screenupdating back on
With Application
.Calculation = lCalc
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub

Using an array to pull multiple variables of data and copy to another worksheet

I have a worksheet that I want to search for a certain criteria in column "A" and once I find the multiple variables I am looking to copy all of those particular rows that are in the array to another worksheet. Here is the code I have, I am having trouble with it copying only the rows from the last number of the array over (seems to me like it is copying on top of each other and only keeping the last number in the array).
Sub Copy_Changed_Rows()
Dim Lastrow As Long
With Sheets("DataDump")
If .Range("A:A").Find("397", , xlValues, xlWhole, , , False) Is Nothing Then
MsgBox "No ""Changed"" rows found. ", , "No Rows Copied": Exit Sub
Else
Application.ScreenUpdating = False
Lastrow = .Range("A" & Rows.Count).End(xlUp).Row + 1
.Range("A1:A" & Lastrow).AutoFilter Field:=1, Criteria1:=Array("397", "437", "509", "646")
.Range("A2:A" & Lastrow).SpecialCells(xlCellTypeVisible).EntireRow.Copy
Sheets("Paste").Range("A2").PasteSpecial xlPasteValues, xlPasteSpecialOperationNone, False, False
.AutoFilterMode = False
'Position on cell A3
With Application
.CutCopyMode = False
.Goto Sheets("Paste").Range("A2")
.ScreenUpdating = True
End With
MsgBox "All matching data has been copied.", , "Copy Complete"
End If
End With
End Sub
What I found was there was one piece missing on the filter at the end of the filter line add , Operator:=xlFilterValues
Sub Copy_Changed_Rows()
Dim Lastrow As Long
With Sheets("DataDump")
If .Range("A:A").Find("397", , xlValues, xlWhole, , , False) Is Nothing Then
MsgBox "No ""Changed"" rows found. ", , "No Rows Copied": Exit Sub
Else
Application.ScreenUpdating = False
Lastrow = .Range("A" & Rows.Count).End(xlUp).Row + 1
.Range("A1:A" & Lastrow).AutoFilter Field:=1, Criteria1:=Array("397", "437", "509", "646"), Operator:=xlFilterValues
.Range("A2:A" & Lastrow).SpecialCells(xlCellTypeVisible).EntireRow.Copy
Sheets("Paste").Range("A2").PasteSpecial xlPasteValues, xlPasteSpecialOperationNone, False, False
.AutoFilterMode = False
'Position on cell A3
With Application
.CutCopyMode = False
.Goto Sheets("Paste").Range("A2")
.ScreenUpdating = True
End With
MsgBox "All matching data has been copied.", , "Copy Complete"
End If
End With

Make PivotTable name dynamic in vb code

In Excel 2010, I recorded a macro of steps to create mulitple pivot tables (some on different sheets). However, I am struggling to get the code to accept a "dynamic" PivotTable name. My code originally wanted to automatically assign the next PivotTable number. For example, "PivotTable23", "PivotTable24", etc. Since I never know what the next number will be in the workbook, I changed it to the following and of course it does not work (I am new to using vb code):
Sub TestContinueSD()
'
' TestContinueSD Macro
'
'
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Stmt_Volumes!R1C1:R46154C42", Version:=xlPivotTableVersion14). _
CreatePivotTable TableDestination:="Sheet1!R3C1", TableName:=PivotTables(1) _
, DefaultVersion:=xlPivotTableVersion14
Sheets("Sheet1").Select
Cells(3, 1).Select
ActiveSheet.PivotTables(1).Name = "TOTAL"
With ActiveSheet.PivotTables("TOTAL").PivotFields("desc")
.Orientation = xlPageField
.Position = 1
End With
ActiveSheet.PivotTables("TOTAL").AddDataField ActiveSheet.PivotTables( _
"TOTAL").PivotFields("id"), "Sum of id", xlSum
With ActiveSheet.PivotTables("TOTAL").PivotFields("Sum of id")
.Caption = "Count of id"
.Function = xlCount
End With
With ActiveSheet.PivotTables("TOTAL").PivotFields("sfreq")
.Orientation = xlColumnField
.Position = 1
End With
With ActiveSheet.PivotTables("TOTAL").PivotFields("txt")
.Orientation = xlPageField
.Position = 1
End With
Rows("1:1").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Selection.Font.Bold = True
With Selection.Font
.Name = "Calibri"
.Size = 14
.Strikethrough = False
.Superscript = False
.Subscript = False
.OutlineFont = False
.Shadow = False
.Underline = xlUnderlineStyleNone
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
.ThemeFont = xlThemeFontMinor
End With
ActiveCell.FormulaR1C1 = "TOTAL (ALL)"
Range("A1:B1").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Selection.Merge
Sheets("Sheet1").Select
Sheets("Sheet1").Name = "SUMMARY"
End Sub
You can set the name of the PivotTable by setting the appropriate parameter of the CreatePivotTable method call:
ActiveWorkbook.PivotCaches.Create(...). _
CreatePivotTable TableDestination:="Sheet1!R3C1", TableName:="TOTAL" _
, DefaultVersion:=xlPivotTableVersion14
See http://msdn.microsoft.com/en-us/library/office/ff839885%28v=office.15%29.aspx for details on the CreatePivotTable method.

Activate windows of files stored in arrays, but getting subscript out of range error?

Sub Merge()
Dim File As String
Dim AllFiles(), Filename As Variant
Dim count, test, StartRow, LastRow, LastColumn As Long
Dim LastCell As Variant
test = 0
ChDir "C:\" 'Insert suitable directory for your computer ex:ChDir "C:\Users\Jerry Hou\" if file of interest is in "Jerry Hou" Folder
ReDim AllFiles(1)
Do
Application.EnableCancelKey = xlDisabled
File = Application.GetOpenFilename("XML Files (*.xml),*.xml", 1, "Select File to be Merged") 'Needs to select in Order to merge files
Application.EnableCancelKey = xlErrorHandler
If (File = "False") Then Exit Do
ReDim Preserve AllFiles(count) 'Preserve ?
AllFiles(count) = File 'File== file name and directory
count = (count + 1)
If (MsgBox("Select Another File To be Merged With?", vbQuestion + vbOKCancel, "Merge Files") = vbCancel) Then Exit Do
Loop 'Select Cancel in MsgBox to finish merge file(s) selection
If (count = 0) Then
MsgBox "No selection" 'If you hit Exit from open prompt window
Exit Sub
End If
For count = 0 To UBound(AllFiles)
MsgBox "User selected file name: " & AllFiles(count)
Next
test = count
For test = UBound(AllFiles) To LBound(AllFiles) Step -1
Workbooks.Open Filename:=AllFiles(test)
Next
ReDim AllFiles(count)
test = 2
Do While (test <= count)
Filename = AllFiles(test)
Workbooks(AllFiles(test)).Activate 'ERROR Brings 2nd file that the user had selected to Last xml file selected in order to Front
'Copy and Paste TMG tab
Sheets("TMG_4 0").Activate
StartRow = 2
LastRow = Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
LastColumn = Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
LastCell = Cells(LastRow, LastColumn).Address 'Find lastcell of to be copied file
Range("A2:" & LastCell).Select
Selection.Copy
Windows("Allfiles(1).xml").Activate 'ERROR
Sheets("TMG_4 0").Activate
LastRow = Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
LastRow = LastRow + 1
Range("LastRow").Select 'ERROR
ActiveSheet.Paste
'Copy and Paste Gamma tab
Sheets("GammaCPS 0").Activate
StartRow = 2
LastRow = Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
LastColumn = Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
LastCell = Cells(LastRow, LastColumn).Address
Range("A2:" & LastCell).Select
Selection.Copy
Windows("Allfiles(1).xml").Activate 'ERROR Windows("File_name.xlsm").activate
Sheets("GammaCPS 0").Activate
LastRow = Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
LastRow = LastRow + 1
Range("LastRow").Select 'ERROR
ActiveSheet.Paste
test = test + 1
Loop
Windows("Allfiles(1).xml").Activate 'ERROR
ActiveWorkbook.SaveAs Filename:="C:\" & AllFiles(1) & AllFiles(test) & ".xlsm", FileFormat:=52
End Sub
You redim AllFiles but never fill it with anything. Is there missing code?
AllFiles is a 0 based array so if you want to start at the second element you need to use test = 1 instead of test = 2.
For looping through an array, try this:
For test = 1 to ubound(AllFiles) - 1 'This loops through the array from the second element to the last
Is "LastRow" a named range? If not, that's not going to work. The following will select the last used row in a worksheet:
activesheet.Rows(activesheet.usedrange.rows.count).select
Your SaveAs is failing because 1) AllFiles looks like it's never filled and 2) your save path as you wrote would be literally: C:\Allfile(1)&Allfiles(count)\.xlsm. You want:
ActiveWorkbook.SaveAs Filename:= "C:\" & AllFiles(1) & AllFiles(test) & ".xlsm"
EDIT After Code Update
You never initialize your count variable, add count = 0 to the beginning just to be safe.
GetOpenFilename does in fact return the full path. Once you have that path stored in a variable (such as AllFiles()) you can get just the filename portion with mid(AllFiles(test), instrrev(AllFiles(test), "\") + 1)
You don't need the ReDim AllFiles(count) prior to your main Do Loop. ReDim erases the contents of the array unless you use the Preserve keyword.
Change Workbooks(AllFiles(test)).Activate to Workbooks(Mid(AllFiles(test), InStrRev(AllFiles(test), "\") + 1)).Activate to strip the path information and leave just the filename.
Windows("Allfiles(1).xml").Activate won't work since your sending a literal string. You want WORKBOOKS(Mid(AllFiles(1), InStrRev(AllFiles(1), "\") + 1)).Activate here again.
LastRow = LastRow + 1 probably isn't what you meant. Try Set LastRow = LastRow.Offset(1, 0)
Change Range("LastRow").Select to LastRow.select
All instances of Windows( should be changed to Workbooks(

Resources