Saving File Path Using File Picker - vba

I have written the below code via a user form with buttons. On the form, I have created three (3) separate command buttons that are to save different file paths to open existing excel workbooks. The idea is to have vba automatically open/close workbooks in a completely automated fashion.
Dim SCDMMRReport As FileDialog
Dim ActionClicked As Boolean
Set SCDMMRReport = Application.FileDialog(msoFileDialogFilePicker)
SCDMMRReport.InitialFileName = "J:\INS\CAS\G22 PRT Report"
SCDMMRReport.AllowMultiSelect = False
ActionClicked = SCDMMRReport.Show
If ActionClicked Then
SCDMMRReportCommandButton.Visible = False
SCDMMRReportLabel.BackColor = rgbLightGreen
SCDMMRCheckBox = True
Else
MsgBox ("No file selected!")
SCDMMRReportCommandButton.BackColor = rgbPink
SCDMMRReportLabel.BackColor = rgbPink
End If
Everything appears as it runs excellent, however when it comes time to call on this code later in the script (when I hit the execute command button), the file paths are not saved. Any advice is greatly appreciated!
Thanks,
Derek

Related

Excel VBA: Importing/browsing files in folder

I have a concerned regarding importing/browsing files using VBA. It is working as expected, I can import or select files from the folder. However, there is a dialog box popped out every time I processed the selected file (see image below). Is it possible to remove this dialog box? Or is it because the file is too large to handle?
Here is my code for selecting the file from the folder:
Dim FSO As Object
Dim FD As Object
Set FSO = CreateObject("scripting.filesystemobject")
Set FD = Application.FileDialog(msoFileDialogFilePicker)
'select/browse file in folder path
If FD.Show = -1 Then
Filename = FD.SelectedItems(1)
Filename = FSO.getfile(Filename)
End If
txtBoxOld.Text = Filename
Thank you.
Setting Application.DisplayAlerts = True is a bit like just sticking your fingers in your ears and saying I CAN'T HEAR YOU. The problem is that it will mute every alert, not just the one you're concerned about.
If you want to purge the clipboard before the end of the subroutine, use Application.CutCopyMode=False and you won't get the error.

Load template and attach chosen file

The aim of this project is to:
Load template from network personal drive (currently working)
Open Dialog Window, using Word (as that loads quicker for me), set to a different network folder (function achieved - just)
Choose and attach user chosen file (prefered option for multi-file selection but that was to complex and thus beyond the time I can afford to dedicate to the project)
Using previous filepath, build and apply the subject line based on the file name. (currently working)
The macro is called by a button in the Quick Access or Main Tool Bars.
The problems:
when the "Browse" window appears, it does so behind outlook/hidden UNLESS the macro code has been viewed in the editor at some time since Outlook was opened; every fix either show the entire Word program or seems to have no effect.
when you choose a file in the "Browse" and then click "OK", a second "Browse" window opens where you have to choose a file again and this time click "Open"; this second file is then the one that is attached to the email.<--FIXED
System Details (even though not all will be of importance)
Windows 7 64bit
Office Professional 2010
The Code
Sub New_Orders_Email()
Dim NewMail As Outlook.MailItem
Dim otherObject As Word.Application
Dim fd As Office.FileDialog
Dim fileaddress As String
Dim filename As String
On Error GoTo Final
'Set template to use
Set NewMail = Application.CreateItemFromTemplate("P:\Office Templates\Orders SCI - 1617.oft")
'Set to use Word for Attach File Dialog
Set otherObject = New Word.Application
otherObject.Visible = False
Set fd = otherObject.Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.InitialFileName = "R:\Science\Technician Documents\Budgets & Orders\2016 - 2017\Orders\"
.Show
End With
fd.Show
fileaddress = fd.SelectedItems(1)
'Aquire File Name in correct form for Subject Line
Dim MidStart As Long
MidStart = InStrRev(fileaddress, "\") + 16
Dim MidEnd As Long
MidEnd = InStrRev(fileaddress, ".")
filename = Mid(fileaddress, MidStart, MidEnd - MidStart)
'Load template, attach single file and apply correct Subject
NewMail.Display
NewMail.Attachments.Add (fileaddress)
NewMail.Subject = "Order No: " + filename
otherObject.Quit
Set otherObject = Nothing
Final:
End Sub
Your file Dialog is probably not shown, because of the line "otherObject.Visible = False"
Number (2) might be solved if you delete one of your "fd.Show". Looks like you call it twice...

Save Excel Sheet text only to text file VBA

I am trying to copy the values of one column in a sheet to a text file. The code I currently have causes runtime error 434.
Sheets("Output to fcf.1").Columns("A").SaveToText "P:\4_Calcs\02. Flag Mapping\test_.txt"
If I try and save the whole sheet
Sheets("Output to fcf.2").SaveToText "P:\Clear Project Drive\CLE10276 AWS SMP Model Assessmnts\4_Calcs\02. Flag Mapping\test2_.txt"
I get the entire sheet converted into text rather than just the text in the sheet. Is there a simple way to do this?
Thanks in advance!
Not sure which Excel version you have but I don't see a method for SaveToText.
But this procedure should work, or at least get you started...
Sub SaveColumn(sheetName As String, columnName As String, fileName As String)
Dim cell
Dim fso
Dim file
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.CreateTextFile(fileName, True)
For Each cell In Sheets(sheetName).Columns(columnName).Cells
If cell.Value <> "" Then
file.WriteLine cell.Value
End If
Next
file.Close
Set file = Nothing
Set fso = Nothing
End Sub
To call it...
SaveColumn "Output to fcf.1", "A", "P:\4_Calcs\02. Flag Mapping\test_.txt"
This is designed to be used as a macro.
Step by step guide:
1) From excel, hit Alt+F11 on your keyboard.
2) From the menu bar, click Insert, then Module
3) Copy and paste the code provided below into the new module that opens.
NOTE: DocPath = "C:\docs\data.txt" should be wherever you want the output file saved, including the file's actual name. Remember, the folder you want the output file to be located in should ALREADY exist. This does not create the folder if it can't be found.
4) From the menu bar, click Tools, then References. Make sure both "Microsoft Office 14.0 Object Library" as well as "Microsoft Word 14.0 Object Library" are checked, and hit okay (See screenshot for details)
5) Save the document as an .xlsm file (This file type supports Macros)
6) Close the VBA editor. Back in Excel, on the ribbon click View and then Macros. Your new macro should be in the list as ExportToTXT
7) Select it and hit run.
Sub ExportToTXT()
Dim DocPath As String
Dim MsgBoxCompleted
Columns("A").Select
Dim AppWord As Word.Application
Set AppWord = CreateObject("Word.Application")
AppWord.Visible = False
Selection.Copy
DocPath = "C:\docs\data.txt"
'Create and save txt file
AppWord.Documents.Add
AppWord.Selection.Paste
AppWord.ActiveDocument.SaveAs2 Filename:=DocPath, FileFormat:=wdFormatText
Application.CutCopyMode = False
AppWord.Quit (wdDoNotSaveChanges)
Set AppWord = Nothing
MsgBoxCompleted = MsgBox("Process complete.", vbOKOnly, "Process complete")
End Sub
Good luck, and if you have any questions, don't hesitate to ask.
NOTE: These directions might seem overly simplified for your skill level, but I wrote the answer like this to potentially help others in the future.
EDIT
Change
DocPath = "C:\docs\data.txt"
to
DocPath = "C:\docs\data.fcf"
And change
AppWord.ActiveDocument.SaveAs2 Filename:=DocPath, FileFormat:=wdFormatText
to
AppWord.ActiveDocument.SaveAs2 Filename:=DocPath
The output file will be .fcf format. Whether or not it will open properly is something I'm not sure of. You'd have to test in the program you're using.

Vba-how to open csv file among several csv files and make this file active from the sharepoint site(.aspx not sharedrive) for next steps

I have three files one is a excel file enabled with macro where my macro is(1), the csv file to run the macro on(2). The new csv file that would be opened(3)
I am new to userform I created a web browser control and was able to initialize in the userform and added the code
Private Sub UserForm_Initialize()
Me.WebBrowser1.Navigate "http://sharepoint_site.aspx"
End Sub
now when I click on the required csv file I get file download. There how do I just open the file and make this newly opened csv file as active? There are many csv files on the sharepoint site.The user selects a specific file and gets a file download box where it should jusst open that csv file. The reason for using userform as suggested by #David was to better control the newly opened CSV file and have the name of the file stored to perform the next steps of the code rather than file 2 where the macro is run to be the active workbook.Below code was my previous code which was part of a case statement.
Dim IE As Object
Set IE = CreateObject("InternetExplorer.application")
With IE
.Visible = True
.navigate ("https://site.aspx")
MsgBox "Select the file and click open file"
Here obviously activated the file (2) where the macro ran but wanted to activate the newly opened file. Any help on this is greatly appreciated & thank you in advance.
Try something like this instead of the WebBrowser control, my apologies for pointing you in the wrong direction:
Sub foo()
Dim SummaryWB As Workbook
Dim vrtSelectedItem As Variant
With Application.FileDialog(msoFileDialogOpen)
.InitialFileName = "https:\\your_sharepoint\team\folder" & "\"
.AllowMultiSelect = False
.Show
For Each vrtSelectedItem In .SelectedItems
Set SummaryWB = Workbooks.Open(vrtSelectedItem)
Next
End With
If SummaryWB Is Nothing Then Exit Sub
Call SomeOtherMacro(SummaryWB)
End Sub
So then you have some other macro that will process this workbook, you send the workbook to it like the above Call statement, and make sure that the other procedure accepts a Workbook:
Sub SomeOtherMacro(wb as Workbook)
' This macro will do something to the workbook
wb.Worksheets(1).Select
MsgBox wb.Name & " sheet 1 is now selected!"
End Sub
Modified from this answer.

Is it possible to associate an Excel Macro with a file extension?

I have built a macro for building and running SQL Queries. I am pretty happy with it so far. The only thing I would like to add is the ability in Windows to double click a .sql file and it opens inside the macro. Sample is below:
This is the code that opens an SQL file when Load Query is pressed.
Sub LoadQuery()
Dim fNameAndPath As Variant
fNameAndPath = Application.GetOpenFilename(FileFilter:="SQL Query Files (*.sql), *.sql", Title:="Select File To Be Opened")
If fNameAndPath = False Then Exit Sub
Open fNameAndPath For Input As #1
Sheets("Sheet1").SQL_Query = Input$(LOF(1), 1)
Close #1
Sheets("Sheet1").SQLFileName.Caption = fNameAndPath
End Sub
Is this even possible? I don't think it will be but thought I would check with you guys first.
What have I tried so far? Nothing, because I don't even know where to start, Uncle Google didn't hook a brother up in fact he just confused me even more.
Using the ideas below I went with this:
Option Explicit
Dim xlApp, xlBook, fNameAndPath
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("G:\Analytics Reporting Archive\SQL Client.xlsm", 0, True)
xlApp.Open WScript.Arguments(0) For Input As #1
xlBook.Sheets("Sheet1").SQL_Query = Input$(LOF(1), 1)
xlApp.Close #1
xlBook.Sheets("Sheet1").SQLFileName.Caption = fNameAndPath
Set xlBook = Nothing
Set xlApp = Nothing
WScript.Quit
This didn't work, it didn't like opening the text file (sql file) so I went with creating a small routine in the Excel app:
Sub LoadQueryDBLClick(QueryFileName As String)
Open QueryFileName For Input As #1
Sheets("Sheet1").SQL_Query = Input$(LOF(1), 1)
Close #1
Sheets("Sheet1").SQLFileName.Caption = fNameAndPath
End Sub
This is then called in the VBS like so:
Option Explicit
Dim xlApp, xlBook, fNameAndPath
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("G:\Analytics Reporting Archive\SQL Client.xlsm", 0, True)
xlApp.Run "LoadQueryDBLClick " & WScript.Arguments(0)
Set xlBook = Nothing
Set xlApp = Nothing
WScript.Quit
Brilliant right?
NO :(. It "would" work, of that I am confident (and extremely grateful to you guys that posted replies for me that got me this far) but alas Citrix strikes again:
Error: ActiveX component can't create object: 'Excel.Application'
I am confident that you guys have solved this in that Citrix is now the issue.
See here for how to create a custom extension and associate it with an action.
https://superuser.com/questions/406985/programatically-associate-file-extensions-with-application-on-windows
What might work in your case is to associate the extension with a vbs file which takes the launching SQL filepath as a parameter and opens your Excel file using automation, then loads the SQL file into the workbook.
You'll want to right-click on an SQL file and select Open With. Choose, or browse to Excel.exe. Set it as the default application to open SQL files with.
This will open your SQL files in Excel.
From here you'll need to teach your macro to detect when it was launched by an SQL file and run as desired.