Set cell value based on filename that was copied - excel

I have a large excel file (500+ sheets) where we store a daily report on each sheet, each sheet is used to supply data to one sheet and make graphs.
I am trying to make it so I can drop these reports into a folder, run a macro and then have these copied into the master file. The main file is currently set to make the sheet name the value of A1.
My current problem is that I the value I need to put in A1 is only present in the file name, it is not located in any cell and I have no way of having it added to the report.
The file name of the report is like this - "Daily report for September 21 , 2015.xls"
The code I have will currently copy the file into the master file but I need to be able to change cell value A1 to 9/21/15 in this example using just the "September 21" from the file name.
Here is my current code
Sub test()
Dim Wb1 As Workbook
Dim Wb2 As Workbook
Dim Filename As String
Dim Path As String
Path = "M:\TESTCOPY\" 'CHANGE PATH
Filename = Dir(Path & "\*.xls")
With Application
.ScreenUpdating = False
.EnableEvents = False
.DisplayAlerts = False
End With
Set Wb1 = Workbooks.Open(Path & Filename)
Set Wb2 = ThisWorkbook
Wb1.Sheets.Copy Before:=Wb2.Sheets("LAST")
Wb1.Close False
With Application
.ScreenUpdating = True
.EnableEvents = True
.DisplayAlerts = True
End With
End Sub
It would also be nice to be able to check if sheet 9/21/15 already exists and abort the copy and also be able to delete the worksheet after the copy is done. I know I can use Kill but I am not sure where to place it to kill Wb1 in this code.
Thanks
Edit:
I have gotten something to work but it is rather crude due to my lack of knowledge. I'd like it to be able to loop through the files in a folder if possible and learn how to get rid of the nested replace commands. I could not figure out how to get trim to work correctly or if it works the same to remove the spaces in the middle of the string so that is the reason for the replace commands.
Sub CopyReport()
Dim Wb1 As Workbook
Dim Wb2 As Workbook
Dim Filename As String
Dim Path As String
Dim FileDate As String
Path = "M:\TESTCOPY\" 'CHANGE PATH
Filename = Dir(Path & "\*.xls")
FileDate = Filename
'--------------------------------------------
With Application
.ScreenUpdating = False
.EnableEvents = False
.DisplayAlerts = False
End With
Set Wb1 = Workbooks.Open(Path & Filename)
Set Wb2 = ThisWorkbook
Wb1.Sheets.Copy Before:=Wb2.Sheets("LAST")
Wb1.Close False
With Application
.ScreenUpdating = True
.EnableEvents = True
.DisplayAlerts = True
End With
Cells(1, 1).Value = Replace(Replace(Replace(Replace(Trim(Replace(Replace(FileDate, "Daily report for ", ""), ".xls", "")), ",", " "), " ", " "), " ", " "), " ", ",")
Cells.FormatConditions.Delete
Kill (Path & Filename)
MsgBox Replace(Filename, ".xls", "") & " has been copied and deleted"
End Sub

I do this, try it
Sub Test()
Dim Text As String
Dim MyDate As Date
Dim Data() As String
Text = "Daily report for September 21 , 2015.xls"
Text = Replace(Text, "Daily report for ", "")
Text = Replace(Text, ".xls", "")
Text = Replace(Text, ",", "")
While InStr(Text, " ")
Text = Replace(Text, " ", " ")
Wend
Data = Split(Text, " ")
MyDate = DateValue((Data(1) & "/" & MonthToNumber(Data(0)) & "/" & Data(2)))
End Sub
Function MonthToNumber(ByVal Mo As String) As Integer
Select Case Mo
Case "September"
MonthToNumber = 9
Exit Function
End Select
End Function
Cheers

Related

VBA activeworbook.close 1004 runtime error, missing folder path

Sub LoopThroughFolder()
Dim table As Range
Dim FSO
Dim month As String
Dim year As String
Dim FileName As String
Dim OldFileName As String
Dim MainPath As String
Dim ClientPath As String
Dim FullPath As String
Dim FileToOpen As Workbook
Dim Text As String
Application.ScreenUpdating = False
Set wb = ThisWorkbook
Set ws = wb.Worksheets("FileName")
month = ws.Range("E8")
year = ws.Range("F8")
OldFileName = ws.Range("R5")
MainPath = "C:\Document\documents\CPREIF_daily_test\"
ClientPath = MainPath & year & "\" & month & " - " & year & "\"
Set table = Range("B8", Range("B8").End(xlToRight).End(xlDown))
For Each Row In table.Rows
Text = Row.Cells(1, 1)
FileName = Row.Cells(1, 7)
Set FileToOpen = Workbooks.Open(ClientPath & OldFileName, UpdateLinks:=0)
Range("B4").ClearContents
Range("B4") = Text
Range("B4").NumberFormat = "dddd mmmm d" & ", " & "yyyy"
ActiveWorkbook.Close True, ClientPath & FileName
Next Row
MsgBox "Client Files Turned"
End Sub
Hey All. I wrote VBA to loop through each row of a table, renaming the workbook and changing the date within a cell, based off each row in a table. When I run the code within VBA editor, the code works. When I create a button and assign the macro to the button, I receive a runtime error. The code that breaks is:
ActiveWorkbook.Close True, ClientPath & FileName
Thanks!

Excel VBA Saving with Variable Name

Soo.... having a problem saving the excel with as the name i want it to generate.. it keeps saving as "FALSE"... from what i can tell I have everything correct. Since the directory will be a variable I rather just have it save in the current folder.
Ultimately I want it as Week # m-d-yy Site.xlsm
e.i Week 36 9-5-20 41st HMU
Sub SaveWorkBook()
Dim wb As Workbook
Dim myFile As String
Dim dDate As Date
Dim sSite As String
dDate = Date 'Todays date
sSite = Range("Q10").Value 'Site Name
myFile = "Week " & WorksheetFunction.WeekNum(dDate, 2) & Format(dDate, "m-d-yy") & " " & sSite & ".xlsm"
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs FileName = myFile
End Sub

Best way to read a very large array into excel sheet

I have to import a number of text files into excel and add each text file to a new sheet. The number of lines on some files are in excess of 350,000. Loops take so long that it's not really user friendly. I've tried using this to read the data in quickly
Dim arrLines() As String
Dim lineValue As String
lineValue = ts.ReadAll
DoEvents
arrLines() = Split(lineValue, vbCrLf)
Dim Destination As Range
Set Destination = Worksheets(WorksheetName).Range("A2")
Set Destination = Destination.Resize(UBound(arrLines), 1)
Destination.Value = Application.Transpose(arrLines)
but this results in every value AFTER line 41243 simply having a value of "#N/A". I was thinking to use a Application.Index to split up the array into smaller arrays, but you need to give the index function an array of lines that you want to compose the new array, and that would mean creating a loop to run through the numbers 1-41000, then 41001-82000, etc. At the point i'm doing a loop to create the arrays it's not really faster. looping through the file line by line is similarly too slow. What's a good way of reading in a such a large number of lines without ending up with the missing values?
You could use and automate the 'Data' -> 'From Text/CSV' wizard of Excel.
Using the Macro recorder you end up with this, which should be a good start:
ActiveWorkbook.Queries.Add Name:="MyFile", Formula:="let" & Chr(13) & "" & Chr(10) & " Source = Table.FromColumns({Lines.FromBinary(File.Contents(""C:\Path\MyFile.txt""), null, null, 1252)})" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " Source"
ActiveWorkbook.Worksheets.Add
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:="OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=""MyFile"";Extended Properties=""""", Destination:=Range("$A$1")).QueryTable
.CommandType = xlCmdSql
.CommandText = Array("SELECT * FROM [MyFile]")
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "MyFile"
.Refresh BackgroundQuery:=False
End With
Copy Text Files to Excel
Credits to simple-solution for suggesting (in the comments) to open the text files with Workbooks.Open.
The Code
Sub CopyTextFilesToExcel()
' Search Folder Path
Const cStrPath As String _
= "D:\Excel\MyDocuments\StackOverflow\"
Const cStrExt As String = "*.txt" ' File Extension
Const cFolderPicker As Boolean = False ' True to enable FolderPicker
Dim wb As Workbook ' Current File
Dim strPath As String ' Path of Search Folder (Incl. "\" at the end.)
Dim strFileName As String ' Current File Name
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
On Error GoTo ProcedureExit
' Determine Search Path ("\" Issue)
If cFolderPicker Then
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show = False Then Exit Sub
strPath = .SelectedItems(1) & "\"
End With
Else
If Right(cStrPath, 1) <> "\" Then
strPath = cStrPath & "\"
Else
strPath = cStrPath
End If
End If
' Determine first Current File Name.
strFileName = Dir(strPath & cStrExt)
With ThisWorkbook ' Target Workbook
' Loop through files in folder.
Do While strFileName <> ""
' Create a reference to the Current File.
Set wb = Workbooks.Open(cStrPath & strFileName)
' Copy first worksheet of Current File after the last sheet
' (.Sheets.Count) in Target Workbook.
wb.Worksheets(1).Copy After:=.Worksheets(.Sheets.Count)
' Close Current File without saving changes (False).
wb.Close False
' Find next File(name).
strFileName = Dir()
Loop
End With
MsgBox "All files copied!"
ProcedureExit:
With Application
.ScreenUpdating = True
.DisplayAlerts = True
End With
End Sub
Mathieu Guindon had EXACTLY the solution I was hoping for. Eliminating the transpose has solved the issue with the #N/A values. Thank you!
Edit:
The code just loops the arrayed data a second time into a two dimensional array and then posts it to the range without the transpose effect. It's a little slower than the old way (taking about two minutes or so longer), but it's still pretty fast and produces the results I want. Code is as follows:
lineValue = ts.ReadAll
DoEvents
arrLines() = Split(lineValue, vbCrLf)
Dim arrBetween() As Variant
ReDim arrBetween(UBound(arrLines), 0)
LoopLength = UBound(arrLines) - 1
For i = 0 To LoopLength
arrBetween(i, 0) = arrLines(i)
DoEvents
If i Mod 2500 = 0 Or i = LoopLength Then
Application.StatusBar = "Importing " & WorksheetName & " " & (i) & " ."
End If
Next i
Dim Destination As Range
Set Destination = Worksheets(WorksheetName).Range("A2:A" & UBound(arrLines))
Destination.Value = arrBetween

Excel VBA or Script to run the same macro (refreshes data connection from 1 file & repeats on other files in the same directory)

I'm searching for a code to run the same macro on 200+ files in the same folder directory until the last file is complete.
The macro I have currently does this once I click a button
Refresh .CSV data connection (File Selection window pops up in
the directory, I select the file)
Refreshes Pivot Table
Deletes Specific Tabs
Saves Copy As in another Directory
I want to eliminate me clicking the RUN button 200+ times, and selecting the .CSV file. Would anyone happen to know of a code that could do this?
Current MACRO is:
Sub Load_Brand3()
' Load_Brand3 Macro
Sheets("Data").Select
Range("DATATable[[#Headers],[Datetime]]").Select
Selection.ListObject.TableObject.Refresh
Sheets("Brand Summary").Select
Range("A13").Select
ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh
ActiveSheet.PivotTables("PivotTable1").PivotFields("Retailer.Name").ShowDetail _
= False
Sheets("Brand Summary").Select
Dim SavedCopy As Excel.Workbook
ActiveWorkbook.SaveCopyAs "C:\Users\ME" & Format(Date, "mmddyyyy") & "-" & [A1] & ".xlsm"
Workbooks.Open "C:\Users\ME" & Format(Date, "mmddyyyy") & "-" & [A1] & ".xlsm"
Set SavedCopy = ActiveWorkbook
With SavedCopy
ActiveWorkbook.Connections("BrandExport").Delete
Application.DisplayAlerts = False
.Worksheets("Lookup").Delete
.Worksheets("Count").Delete
Sheets("Brand Summary").Select
Range("A1").Select
Application.DisplayAlerts = True
.Close True
End With
MsgBox ("Your File was saved.")
End Sub
This should be close. Just change MyPath to the correct directory and run ProcessFiles.
Sub ProcessFiles()
Const MyPath As String = "C:\Users\best buy\Data Files\*.csv"
Dim FileName As String
With Application
.ScreenUpdating = False
.Calculation = xlCalculationManual
.DisplayAlerts = False
End With
FileName = Dir(MyPath, vbDirectory)
Do While FileName <> ""
Load_BrandFile FileName
FileName = Dir()
Loop
With Application
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
.DisplayAlerts = True
End With
End Sub
Sub Load_BrandFile(FileName As String)
Dim SavedCopy As Workbook
Dim DATATable As ListObject
Dim PivotTable1 As PivotTable
ThisWorkbook.SaveCopyAs "C:\Users\ME" & Format(Date, "mmddyyyy") & "-" & [A1] & ".xlsm"
Set SavedCopy = Workbooks.Open("C:\Users\ME" & Format(Date, "mmddyyyy") & "-" & [A1] & ".xlsm")
With SavedCopy
Set DATATable = .Worksheets("Data").ListObjects("DATATable")
DATATable.Refresh
Set PivotTable1 = .Worksheets("Brand Summary").PivotTables("PivotTable1")
PivotTable1.PivotCache.Connection = FileName
PivotTable1.PivotFields("Retailer.Name").ShowDetail = False
.Connections("BrandExport").Delete
.Worksheets("Lookup").Delete
.Worksheets("Count").Delete
Application.Goto Reference:=.Worksheets("Brand Summary").Range("A1"), scroll:=True
.Close True
End With
End Sub
Hopefully this sorts it for you.
Sub CycleFolder()
Dim folderSelect As FileDialog
Set folderSelect = Application.FileDialog(msoFileDialogFolderPicker)
With folderSelect
.AllowMultiSelect = False
If .Show <> -1 Then Exit Sub
strItem = .SelectedItems(1)
End With
Files = Dir(strItem & "\")
While Files <> ""
'RUN FUNCTION HERE
'Uncomment next line to test iteration
'Debug.Print Files
Files = Dir
Wend
End Sub

Subscript out of range error 9 vba

I am getting a subscript out of range error when another user runs my add in but have no problems when running the same code myself. This happens when setting a workbook value. The filename is being generated by getting the current date and stored as gendate. From this, the filename is created and saved based on the filepath that the user has made. In this example, the value of gv.Range("b2").text is C:\Users\username\Desktop\ReportGeneration. fp is therefore C:\Users\dmulhausen\Desktop\ReportGeneration\TSReports9_6_201615h5m32s.xlsx
This is not generating an error for me, but it is generating an error for another user of the script.
Dim ai As Workbook 'add in data ---Initialized in Report Setup
Dim dwb As Workbook 'destination workbook ---Initialized in Report Setup
Dim ss As Worksheet 'source sheet
Dim ds As Worksheet 'destination sheet or writing sheet
Dim rv As Worksheet 'reporting variables sheet ---Initialized in Report Setup
Dim pv As Worksheet 'ts variables sheet ---Initialized in Report Setup
Dim gv As Worksheet 'global ai variables ---Initialized in Report Setup
Dim tempstr As String
Dim fp As String 'file path ---Initialized in Report Setup
Dim gendate As Date
Dim reportscreated As Integer
Dim initialized As Boolean
Dim sheetnames(1 To 12) As String
Sub reportsetup()
Set ai = Workbooks("TSReports add in.xlam")
Set rv = ai.Worksheets("ReportVars")
Set pv = ai.Worksheets("TS1_2Vars")
Set gv = ai.Worksheets("globalVars")
If (IsEmpty(gv.Range("b2").Value)) Then
MsgBox ("Please select a designated folder for reports")
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
If .SelectedItems.Count > 0 Then
gv.Range("b2").Value = .SelectedItems(1)
End If
ai.Save
End With
End If
initialized = True
gendate = Now()
tempstr = "TSReports" & Month(gendate) & "_" & Day(gendate) & "_" & Year(gendate) & Hour(gendate) & "h" & Minute(gendate) & "m" & Second(gendate) & "s"
fp = gv.Range("b2").Text & "\" & tempstr & ".xlsx"
Workbooks.Add
Application.DisplayAlerts = False
Application.AlertBeforeOverwriting = False
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:=fp
Set dwb = Workbooks(tempstr) '*******Error occurs here*******
See: Windows().Activate works on every computer except one
This should fix the issue.
tempstr = "TSReports" & Month(gendate) & "_" & Day(gendate) & "_" & _
Year(gendate) & Hour(gendate) & "h" & Minute(gendate) & "m" & _
Second(gendate) & "s" & ".xlsx"
fp = gv.Range("b2").Text & "\" & tempstr
Workbooks.Add
Application.DisplayAlerts = False
Application.AlertBeforeOverwriting = False
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:=fp
Set dwb = Workbooks(tempstr)
However this would be more robust:
Set dwb = Workbooks.Add
Application.DisplayAlerts = False
Application.AlertBeforeOverwriting = False
Application.DisplayAlerts = False
dwb.SaveAs Filename:=fp

Resources