Open the excel new file after complete operation - vba

hi what i am doing right now is scrapping data. after the process complete it will pop msgbox "Completed" and the new file contains the data will be save to network path. my question is. what code do i need to add so that. after the scraping operation complete, it will automatically open the new file created by the scrap tool.
Here is my code
Global FilePath As String
Global strPath As String
Declare Function WNetGetUser Lib "mpr.dll" _
Alias "WNetGetUserA" (ByVal lpName As String, _
ByVal lpUserName As String, lpnLength As Long) As Long
Const NoError = 0
Sub Clear_Internet_Cache()
Shell "RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255"
End Sub
''==========================================================================================
''Copy_Paste function creates the log of excel files with the issues in it
''==========================================================================================
Function Copy_Paste() As String
Dim SourceBook As Workbook
Dim DBook As Workbook
Dim strPath As String
Dim count As Double
Dim name As String
Dim TemplateBook, MyTime, Mydate As String
Dim FileName As String
Dim directoryName As String
Dim FY1 As String
Dim WK As String
Dim MyInput As Integer
Dim layer As String
Dim CrawlerName As String
Dim fixedpath As String
Dim region As String
Dim segment As String
If Sheet1.Cells(2, 6) = "Upload to Sharedrive" Then
fixedpath = "\\"
FY1 = Sheet1.Cells(2, 7)
WK = Sheet1.Cells(2, 8)
MyInput = Sheet9.Cells(3, 26)
CrawlerName = "AIO"
region = "EMEA"
segment = Sheet1.Cells(2, 9)
If MyInput = 1 Then
layer = "Staging"
Else
layer = "Production"
End If
''''''''''''''''''''''''''''''FOR USER NAME
Const lpnLength As Integer = 255
Dim status As Integer
Dim lpName, lpUserName As String
lpUserName = Space$(lpnLength + 1)
status = WNetGetUser(lpName, lpUserName, lpnLength)
If status = NoError Then
lpUserName = Left$(lpUserName, InStr(lpUserName, Chr(0)) - 1)
End If
'''''''''''''''''''''''''''''''''''''''''''
directoryName = fixedpath & "\" & region
If Not DirExists(directoryName) Then
MkDir (directoryName)
End If
directoryName = fixedpath & "\" & region & "\" & segment
If Not DirExists(directoryName) Then
MkDir (directoryName)
End If
directoryName = fixedpath & "\" & region & "\" & segment & "\" & FY1
If Not DirExists(directoryName) Then
MkDir (directoryName)
End If
directoryName = fixedpath & "\" & region & "\" & segment & "\" & FY1 & "\" & WK
If Not DirExists(directoryName) Then
MkDir (directoryName)
End If
directoryName = fixedpath & "\" & region & "\" & segment & "\" & FY1 & "\" & WK & "\" & layer
If Not DirExists(directoryName) Then
MkDir (directoryName)
End If
directoryName = fixedpath & "\" & region & "\" & segment & "\" & FY1 & "\" & WK & "\" & layer & "\" & CrawlerName
If Not DirExists(directoryName) Then
MkDir (directoryName)
End If
strPath = directoryName
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
TemplateBook = "AIO_Report"
TemplateBook = Left(TemplateBook, Len(TemplateBook) - 5)
Mydate = Format(Date, "mmm d yyyy")
MyTime = Format(Time, "hh:mm:ss")
MyTime = Replace(MyTime, ":", "_")
FileName = TemplateBook & "_" & Mydate & "_" & MyTime
FilePath = ""
FilePath = strPath & "\" & FileName & "_" & lpUserName & ".xlsx"
Set SourceBook = ActiveWorkbook
Set DBook = Workbooks.Add
SourceBook.Sheets("Bundle List").Cells.copy Destination:=DBook.Sheets("Sheet1").Cells
DBook.Sheets("Sheet1").name = "Error Report"
Sheets("Error Report").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Range("A1").Select
Selection.EntireRow.Select
Selection.Delete
Range("A1").Select
Selection.EntireRow.Select
Selection.Delete
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
DBook.SaveCopyAs FilePath
DBook.Close False
End If
Sheets("Bundle List").Select
Columns("W:An").Select
Selection.Delete Shift:=xlToLeft
Columns("a").Select
MsgBox ("Completed.")
Application.StatusBar = ""
End Function

If DBook is the file you want left open, then I'd probably change this:
DBook.SaveCopyAs FilePath
DBook.Close False
To:
DBook.SaveAs FilePath
This will leave the workbook open, and you've already saved it. Just keep it open for the user to have their way with. As for SaveCopyAs don't think you need to save a copy of an unsaved workbook, right? Have fun!

Assuming you saved some file such as "xyz.xlsx",
call something like
Shell("cmd /c ..pathto...xyz.xlsx")
what it will do is to launch cmd prompt as a conduit to launching the program
registered for xlsx. It will work for any registered extension such as pdf.

Related

Unicode UTF-8 at VBA

I have this VBA code to convert CSV to XLSX, which seems to work but output Excel have strange strings like "Aço" and "plástico" instead of "Aço" or "plástico". I think solution is to include "Unicode UTF-8", but I couldn't find a way. Any help would be appreciated.
Sub CSVtoXLSX()
Dim xFd As FileDialog
Dim xSPath As String
Dim xCSVFile As String
Dim xWsheet As String
Application.DisplayAlerts = False
Application.StatusBar = True
xWsheet = ActiveWorkbook.Name
Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
xFd.Title = "Select a folder:"
If xFd.Show = -1 Then
xSPath = xFd.SelectedItems(1)
Else
Exit Sub
End If
If Right(xSPath, 1) <> "\" Then xSPath = xSPath + "\"
xCSVFile = Dir(xSPath & "*.csv")
Do While xCSVFile <> ""
Application.StatusBar = "Converting: " & xCSVFile
Workbooks.Open Filename:=xSPath & xCSVFile
ActiveWorkbook.SaveAs Replace(xSPath & xCSVFile, ".csv", ".xlsx", vbTextCompare), xlWorkbookDefault
ActiveWorkbook.Close
Windows(xWsheet).Activate
xCSVFile = Dir
Loop
Application.StatusBar = False
Application.DisplayAlerts = True
End Sub

Accessing files from external hard drive

I have files stored on a WD elements hard drive. On occasions I need to copy files from here onto my pc. When I tested the following macro using both the source and destination folders on the c: drive it works fine. However when I changed the source to the external drive (I:\history\june) it says the files do not exist. How can I access the external drive? Any guidance would be welcome.
Thanks, willi
Sub CopyFiles()
Dim iRow As Integer
Dim sSourcePath As String
Dim sDestinationPath As String
Dim sFileType As String
Dim bContinue As Boolean
bContinue = True
iRow = 2
sSourcePath = "C:\Users\admin\documents\Test1\"
sDestinationPath = "C:\Users\admin\documents\Test2\"
sFileType = ".pdf"
While bContinue
If Len(Range("B" & CStr(iRow)).Value) = 0 Then
MsgBox "Files Copied"
bContinue = False
Else
If Len(Dir(sSourcePath & Range("B" & CStr(iRow)).Value & sFileType)) = 0 Then
Range("C" & CStr(iRow)).Value = "File Does Not Exist"
Range("C" & CStr(iRow)).Font.Bold = True
Else
Range("C" & CStr(iRow)).Value = "File Copied"
Range("C" & CStr(iRow)).Font.Bold = False
If Trim(sDestinationPath) <> "" Then
Dim objFSO
Set objFSO = CreateObject("scripting.filesystemobject")
If objFSO.FolderExists(sDestinationPath) = False Then
MsgBox "The destination folder " & sDestinationPath & " Does Not Exists"
Exit Sub
End If
objFSO.CopyFile Source:=sSourcePath & Range("B" & CStr(iRow)).Value & _
sFileType, Destination:=sDestinationPath
End If
End If
End If
iRow = iRow + 1
Wend
End Sub

VBA Save As Current Filename +01

I'm looking to write a macro to save my current version filename +1 instance of the version. For each new day the version would reset to v01. Ex. Current = DailySheet_20150221v01; Save As = DailySheet_20150221v02; Next Day = DailySheet_20150222v01
While increasing the version number, I am hoping the version won't have to contain the v0 once v10+ has been reached.
I was able to workout how to save the file with today's date:
Sub CopyDailySheet()
Dim datestr As String
datestr = Format(Now, "yyyymmdd")
ActiveWorkbook.SaveAs "D:\Projects\Daily Sheet\DailySheet_" & datestr & ".xlsx"
End Sub
but need additional help in finding the version addition. Could I set the SaveAs to a string, then run it through a For/If - Then set?
Put this out to a couple of my friends and below is their solution:
Sub Copy_DailySheet()
Dim datestr As String, f As String, CurrentFileDate As String, _
CurrentVersion As String, SaveAsDate As String, SaveAsVersion As String
f = ThisWorkbook.FullName
SaveAsDate = Format(Now, "yyyymmdd")
ary = Split(f, "_")
bry = Split(ary(UBound(ary)), "v")
cry = Split(bry(UBound(bry)), ".")
CurrentFileDate = bry(0)
CurrentVersion = cry(0)
SaveAsDate = Format(Now, "yyyymmdd")
If SaveAsDate = CurrentFileDate Then
SaveAsVersion = CurrentVersion + 1
Else
SaveAsVersion = 1
End If
If SaveAsVersion < 10 Then
ThisWorkbook.SaveAs "D:\Projects\Daily Sheet\DailySheet_" & SaveAsDate & "v0" & SaveAsVersion & ".xlsm"
Else
ThisWorkbook.SaveAs "D:\Projects\Daily Sheet\Daily Sheet_" & SaveAsDate & "v" & SaveAsVersion & ".xlsm"
End If
End Sub
Thanks to all those who contributed.
Try this one:
Sub CopyDailySheet()
'Variables declaration
Dim path As String
Dim sht_nm As String
Dim datestr As String
Dim rev As Integer
Dim chk_fil As Boolean
Dim ws As Object
'Variables initialization
path = "D:\Projects\Daily_Sheet"
sht_nm = "DailySheet"
datestr = Format(Now, "yyyymmdd")
rev = 0
'Create new Windows Shell object
Set ws = CreateObject("Wscript.Shell")
'Check the latest existing revision number
Do
rev = rev + 1
chk_fil = ws.Exec("powershell test-path " & path & "\" & sht_nm & "_" & datestr & "v" & Format(rev, "00") & ".*").StdOut.ReadLine
Loop While chk_fil = True
'Save File with new revision number
ActiveWorkbook.SaveAs path & "\" & sht_nm & "_" & datestr & "v" & Format(rev, "00") & ".xlsm"
End Sub
If you have the current filename I would use something like:
Public Function GetNewFileName(s As String) As String
ary = Split(s, "v")
n = "0" & CStr(CLng(ary(1)) + 1)
GetNewFileName = ary(0) & "v" & ary(1)
End Function
Tested with:
Sub MAIN()
strng = GetNewFileName("DailySheet_20150221v02")
MsgBox strng
End Sub

Runtime Error 1004: Method 'Range' of object '_Global' failed

I've seen numerous questions on the issue but none of the solutions fit my situation (I think) so any help is appreciated. I receive the error when setting the value of the LR integer variable. As with many others having this issue, it only fails the second time the subroutine is run.
Sub SaveEmailAttachments()
' Creates each variable to be used
Dim xlApp As Excel.Application, xlWB As Excel.Workbook, xlAtt As Excel.Workbook
Dim olItem As Outlook.MailItem
Dim LR As Integer, NR As Integer, j As Integer, intDir As Integer, random As Integer
' Path to the HWB Master template to be used
Const strPath As String = "C:\Users\dkirksey\Documents\SOF\SOF Station HWB Master w Macro.xlsm"
' If no emails are selected, present an error and exit
If Application.ActiveExplorer.Selection.Count = 0 Then
MsgBox "No Items selected!", vbCritical, "Error"
Exit Sub
End If
' Creates a new Excel application
On Error Resume Next
Set xlApp = New Excel.Application
xlApp.Visible = False
'Opens the Excel workbook
On Error GoTo 0
Set xlWB = xlApp.Workbooks.Open(strPath)
'Creates a new directory to store today's information
intDir = (fIsFileDIR("C:\Users\dkirksey\Documents\SOF\HWB Files\" & Format(Now, "mmddyy"), vbDirectory))
If intDir = 0 Then
MkDir ("C:\Users\dkirksey\Documents\SOF\HWB Files\" & Format(Now, "mmddyy"))
MkDir ("C:\Users\dkirksey\Documents\SOF\HWB Files\" & Format(Now, "mmddyy") & "\HWBs")
'Process each selected email
For Each olItem In Application.ActiveExplorer.Selection
j = j + 1
For cnt = 1 To olItem.Attachments.Count
If Right(olItem.Attachments(1).FileName, 4) = "xlsx" Or Right(olItem.Attachments(1).FileName, 3) = "xls" Or Right(olItem.Attachments(1).FileName, 4) = "xlsm" Then
olItem.Attachments(cnt).SaveAsFile ("C:\Users\dkirksey\Documents\SOF\HWB Files\" & Format(Now, "mmddyy") & "\HWBs\" _
& Format(Now, "mmddyy") & " " & j & olItem.Attachments(cnt).DisplayName)
Set xlAtt = xlApp.Workbooks.Open("C:\Users\dkirksey\Documents\SOF\HWB Files\" & Format(Now, "mmddyy") & "\HWBs\" _
& Format(Now, "mmddyy") & " " & j & olItem.Attachments(cnt).DisplayName)
xlAtt.Activate
If xlAtt.ActiveSheet.Range("A3").Value = "HWB" And xlAtt.ActiveSheet.Range("B3").Value = "Instruction (optional)" And xlAtt.ActiveSheet.Range("C3").Value = "Route (optional)" Then
LR = xlAtt.ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
xlAtt.ActiveSheet.Range("A4:C4" & LR).Select
Selection.Copy
xlWB.Activate
xlWB.ActiveSheet.Range("A" & Rows.Count).End(xlUp).Offset(1).Select
Selection.PasteSpecial xlPasteValues
xlWB.ActiveSheet.Cells(1, 1).Activate
End If
xlApp.DisplayAlerts = False
xlAtt.Close SaveChanges:=False
Else
olItem.Categories = "Purple Category"
End If
Next
Next olItem
j = 4
LR = xlWB.ActiveSheet.UsedRange.Rows.Count
Do Until j > LR
If IsNumeric(Cells(j, 1)) = False Then
Cells(j, 1).EntireRow.Delete
LR = LR - 1
ElseIf Cells(j, 1).Value = "" Then
Cells(j, 1).EntireRow.Delete
LR = LR - 1
Else
j = j + 1
End If
Loop
xlWB.SaveAs ("C:\Users\dkirksey\Documents\SOF\HWB Files\" & Format(Now, "mmddyy") & "\" & Format(Now, "mmddyy") & " Complete HWB List")
Else
ans = MsgBox("You have already run SOF today, would you like to continue anyway?", vbYesNo)
If ans = vbYes Then
random = Int((9999 - 100 + 1) * Rnd + 100)
MkDir ("C:\Users\dkirksey\Documents\SOF\HWB Files\" & Format(Now, "mmddyy") & random)
MkDir ("C:\Users\dkirksey\Documents\SOF\HWB Files\" & Format(Now, "mmddyy") & random & "\HWBs")
MsgBox "Your new folder is titled " & Format(Now, "mmddyy") & random & ", it is located in the Documents\SOF\HWB Files directory"
'Process each selected email
For Each olItem In Application.ActiveExplorer.Selection
j = j + 1
For cnt = 1 To olItem.Attachments.Count
If Right(olItem.Attachments(1).FileName, 4) = "xlsx" Or Right(olItem.Attachments(1).FileName, 3) = "xls" Or Right(olItem.Attachments(1).FileName, 4) = "xlsm" Then
olItem.Attachments(cnt).SaveAsFile ("C:\Users\dkirksey\Documents\SOF\HWB Files\" & Format(Now, "mmddyy") & random & "\HWBs\" _
& Format(Now, "mmddyy") & " " & j & olItem.Attachments(cnt).DisplayName)
Set xlAtt = xlApp.Workbooks.Open("C:\Users\dkirksey\Documents\SOF\HWB Files\" & Format(Now, "mmddyy") & random & "\HWBs\" _
& Format(Now, "mmddyy") & " " & j & olItem.Attachments(cnt).DisplayName)
xlAtt.Activate
If xlAtt.ActiveSheet.Range("A3").Value = "HWB" And xlAtt.ActiveSheet.Range("B3").Value = "Instruction (optional)" And xlAtt.ActiveSheet.Range("C3").Value = "Route (optional)" Then
LR = xlAtt.ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
xlAtt.ActiveSheet.Range("A4:C4" & LR).Select
Selection.Copy
xlWB.Activate
xlWB.ActiveSheet.Range("A" & Rows.Count).End(xlUp).Offset(1).Select
Selection.PasteSpecial xlPasteValues
xlWB.ActiveSheet.Cells(1, 1).Activate
End If
xlApp.DisplayAlerts = False
xlAtt.Close SaveChanges:=False
Else
olItem.Categories = "Purple Category"
End If
Next
Next olItem
j = 4
LR = xlWB.ActiveSheet.UsedRange.Rows.Count
Do Until j > LR
If IsNumeric(Cells(j, 1)) = False Then
Cells(j, 1).EntireRow.Delete
LR = LR - 1
ElseIf Cells(j, 1).Value = "" Then
Cells(j, 1).EntireRow.Delete
LR = LR - 1
Else
j = j + 1
End If
Loop
xlWB.SaveAs ("C:\Users\dkirksey\Documents\SOF\HWB Files\" & Format(Now, "mmddyy") & random & "\" & Format(Now, "mmddyy") & " Complete HWB List")
Else
xlWB.Close
xlApp.DisplayAlerts = True
xlApp.Quit
Exit Sub
End If
End If
xlWB.Close
xlApp.DisplayAlerts = True
xlApp.Quit
MsgBox "Well played !"
End Sub
I'm a rookie with VBA so excuse any redundant or just plain idiotic coding methods you notice.
The subroutine works perfectly the first time it is run, just not the second. Please help.
Thank you.

List of all files in Folder / Sub Folder with Hyperlink

I am using this code to list out files in folder and sub-folder. The code is working fine. But if there is no sub-folder I get an error in the below line.
'Files under current dir
fname = Dir(fPath & "*." & fType).
And I want message-box option (Yes/no) for empty folders. (Currently its showing all empty folders)
Public oldNR As Long
Sub HyperlinkDirectory()
Dim fPath As String
Dim fType As String
Dim fname As String
Dim NR As Long
Dim AddLinks As Boolean
'Select folder
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.InitialFileName = "C:\2009\"
.Show
If .SelectedItems.Count > 0 Then
fPath = .SelectedItems(1) & "\"
Else
Exit Sub
End If
End With
'Types of files
fType = Application.InputBox("What kind of files? Type the file extension to collect" _
& vbLf & vbLf & "(Example: xls, doc, txt, pdf, *)", "File Type", "PDF", Type:=2)
If fType = "False" Then Exit Sub
'Option to create hyperlinks
AddLinks = MsgBox("Add hyperlinks to the file listing?", vbYesNo) = vbYes
'Create report
Application.ScreenUpdating = False
NR = 4
With ActiveSheet
.Range("A:C").Clear
.[A2] = "LIST OF FILES"
.[B2] = "Modified Date"
Call FindFilesAndAddLinks(fPath, fType, NR, AddLinks)
End With
With ActiveSheet
.Range("A:B").Columns.AutoFit
.Range("B:B").HorizontalAlignment = xlCenter
Range("B:B").Select
Selection.NumberFormat = "d-mmm-yy h:mm AM/pm"
End With
With ActiveSheet
Range("A2").Select
Selection.Font.Bold = True
Range("B2").Select
Selection.Font.Bold = True
Columns("A:A").Select
Selection.Font.Underline = xlUnderlineStyleNone
End With
Application.ScreenUpdating = True
End Sub
Private Sub FindFilesAndAddLinks(fPath As String, fType As String, ByRef NR As Long, AddLinks As Boolean)
Dim fname As String
Dim oFS As New FileSystemObject
Dim oDir
'Files under current dir
fname = Dir(fPath & "*." & fType)
With ActiveSheet
'Write folder name
.Range("A" & NR) = fPath
.Range("A" & NR).Select
If AddLinks Then .Hyperlinks.Add Anchor:=Selection, _
Address:=fPath, _
TextToDisplay:="FOLDER NAME: " & " " & UCase(Split(fPath, "\")(UBound(Split(fPath, "\")) - 1))
Selection.Font.Bold = True
Selection.Font.Size = 10
Selection.Font.Name = "Arial"
Selection.Font.Underline = xlUnderlineStyleNone
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent3
.TintAndShade = 0.399975585192419
.PatternTintAndShade = 0
End With
With Selection.Font
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
End With
NR = NR + 2
Do While Len(fname) > 0
'filename
If .Range("A" & NR) <> "" Then Debug.Print "Overwriting " & NR
.Range("A" & NR) = fname
'modified
.Range("B" & NR) = FileDateTime(fPath & fname)
'hyperlink
.Range("A" & NR).Select
If AddLinks Then .Hyperlinks.Add Anchor:=Selection, _
Address:=fPath & fname, _
TextToDisplay:=fname
'set for next entry
NR = NR + 1
fname = Dir
Loop
'Files under sub dir
Set oDir = oFS.GetFolder(fPath)
For Each oSub In oDir.SubFolders
NR = NR + 1
Call FindFilesAndAddLinks(oSub.Path & "\", fType, NR, AddLinks)
Next oSub
End With
ActiveWindow.DisplayGridlines = False
End Sub