My goal is to export excel file to txt file format. The idea is to has a GUI to let user select the excel file that she/he wish to export and she/he can decide which file path and file name to save. Once users has finish input and output setting, he/she just need to click Export text button to export the excel file to txt file and save in the location that he/she has decided. The GUI as below
I've a macro to convert excel file to txt format
Private Sub ConvertToText()
ActiveWorkbook.SaveAs FileName:="C:\Projects\ExelToText\Text.txt", FileFormat:=xlCurrentPlatformText, CreateBackup:=False
End Sub
My question is how could I pass value from FileInput and FileOutput as variable to above macro instead harcode the filepath. Appreciate your helps and if you have any better suggestions, please share it out. Thanks
Below is the full source code
Private Sub ReadButton_Click()
OpenWorkbookUsingFileDialog
End Sub
------------------------------
Private Sub WriteButton_Click()
WriteWorkbookUsingFileDialog
End Sub
------------------------------
Private Sub ExportButton_Click()
ConvertToText
End Sub
------------------------------
Private Sub OpenWorkbookUsingFileDialog()
Dim fdl As FileDialog
Dim FileName As String
Dim FileChosen As Integer
Set fdl = Application.FileDialog(msoFileDialogFilePicker)
fdl.Title = "Please Select a Excel File"
fdl.InitialFileName = "c:\"
fdl.InitialView = msoFileDialogViewSmallIcons
fdl.Filters.Clear
fdl.Filters.Add "Excel Files", "*.xlsx; *.xls"
FileChosen = fdl.Show
If FileChosen <> -1 Then
MsgBox "You have choosen nothing"
ReadTextBox = Null
Else
MsgBox fdl.SelectedItems(1)
FileName = fdl.SelectedItems(1)
ReadTextBox = FileName
End If
End Sub
-----------------------------------
Private Sub WriteWorkbookUsingFileDialog()
Dim file_name As Variant
file_name = Application.GetSaveAsFilename( _
FileFilter:="Text Files,*.txt,All Files,*.*", _
Title:="Save As File Name")
If file_name = False Then Exit Sub
If LCase$(Right$(file_name, 4)) <> ".txt" Then
file_name = file_name & ".txt"
End If
WriteTextBox = file_name
End Sub
----------------------------
Private Sub ConvertToText()
ActiveWorkbook.SaveAs FileName:="C:\Projects\ExelToText\Text.txt",FileFormat:=xlCurrentPlatformText, CreateBackup:=False
End Sub
Make it so your subroutine ConvertToText requires a file path/string argument:
Private Sub ConvertToText(sourcePath as String, destPath as String)
Dim wb as Workbook
Set wb = Workbooks.Open(sourcePath)
wb.SaveAs FileName:=destPath,
FileFormat:=xlCurrentPlatformText, CreateBackup:=False
wb.Close
End Sub
Then, make small modifications to your ExportButton to send this parameter to the ConvertToText sub:
Private Sub ExportButton_Click()
On Error Resume Next
ConvertToText Me.TextBox1.Value, Me.TextBox2.Value 'Modify this so that it refers to the TextBoxes on your form
If Err.Number <> 0 Then
MsgBox "Unable to convert file. Please ensure a valid file was entered.", vbCritical
End If
On Error GoTo 0
End Sub
Related
I have some code in a Excel VBA macro and it seems like its persisting values between sessions. The issue is with the BtnUpdate_Click event, the message box doesnt trigger even if the file path in NewDataFilePath is invalid.
Public NewDataFilePath As String
Private Sub BtnFileBrowse_Click()
Dim fdlg As FileDialog
Set fdlg = Application.FileDialog(msoFileDialogOpen)
fdlg.Title = "Select New Dataset"
fdlg.Filters.Clear
fdlg.Filters.Add "Excel Files Only", "*.xls; *.xlsx"
fdlg.Show
If fdlg.SelectedItems.Count <> 0 Then
TxtFilePath = fdlg.SelectedItems(1)
End If
NewDataFilePath = TxtFilePath.Text
End Sub
Private Sub BtnUpdate_Click()
Dim a As String
a = Dir(NewDataFilePath)
If Not Dir(NewDataFilePath) <> "" Then
MsgBox """ & NewDataFilePath & "" is not a valid file path"
End If
End Sub
I added the string a in the event handler to try and debug the code and its showing me some interesting results:
I have a breakpoint on the if statement in BtnUpdate_Click.
Then i stop debugging the macro and re-run it. if i invoke BtnUpdate_Click without selecting another file the Dir() function seems to keep the last file name:
Any ideas why this could happen?
Of course there is no persistence of any variable value once you stop a macro
While the observed behavior is due to the following:
1) FileDialog object keeps the last path chosen in its IntialFileName property
2) Dir(path) function with an empty string as "path" would return the first file in the IntialFileName path stored by last FileDialog run
so when you re-run the macro:
NewDataFilePath is an empty string
a = Dir(NewDataFilePath), would return the first file in the IntialFileName path matching the filters (if any)
What above as the answer to your question
While you could consider the following "nuance" of your code:
Private Sub BtnUpdate_Click()
If NewDataFilePath <> "" Then 'if 'NewDataFilePath' has been set
Dim a As String
a = Dir(NewDataFilePath)
If Not Dir(NewDataFilePath) <> "" Then MsgBox """ & NewDataFilePath & "" is not a valid file path"
Else 'otherwise
MsgBox "No file path specified!", vbCritical ' inform the user to do so
End If
End Sub
Try this code
Public NewDataFilePath As String
Private Sub BtnFileBrowse_Click()
Dim fdlg As FileDialog
Set fdlg = Application.FileDialog(msoFileDialogOpen)
fdlg.Title = "Select New Dataset"
fdlg.Filters.Clear
fdlg.Filters.Add "Excel Files Only", "*.xls; *.xlsx"
fdlg.Show
If fdlg.SelectedItems.Count <> 0 Then
NewDataFilePath = fdlg.SelectedItems(1)
End If
End Sub
Private Sub BtnUpdate_Click()
Dim a As String
a = Dir(NewDataFilePath)
If DoesFileExist(NewDataFilePath) And NewDataFilePath <> "" Then
MsgBox NewDataFilePath & " is a valid file path"
Else
MsgBox NewDataFilePath & " NOT a valid file path"
End If
End Sub
Function DoesFileExist(filePath) As Boolean
DoesFileExist = Dir(filePath) <> ""
End Function
I wrote a script to download files using VBA. The VBA script has to download items that start with https://collaboration.company.corp/collrooms/specificfolder or with \collaboration.company.corp#SSL\DavWWWRoot\collrooms\specificfolder
The specific folders are the same.
If I allow the script to select the specific mapping, it will only recognize it if I use the definition \collaboration.company.corp#SSL\DavWWWRoot\collrooms\specificfolder
How can I create a mapping in VBA to tell Excel that https://collaboration.company.corp/collrooms/specificfolder and \collaboration.company.corp#SSL\DavWWWRoot\collrooms\specificfolder is the same and that the first specification is also valid?
My code:
Option Explicit
Sub FolderSelection()
'Shows the folder picker dialog in order the user to select the folder
'in which the downloaded files will be saved.
Dim FoldersPath As String
'Show the folder picker dialog.
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select a folder to save your files..."
.Show
If .SelectedItems.Count = 0 Then
Sheets("Main").Range("B4") = "-"
MsgBox "You did't select a folder!", vbExclamation, "Canceled"
Exit Sub
Else
FoldersPath = .SelectedItems(1)
End If
End With
'Pass the folder's path to the cell. HERE I AM MISSING THE MAPPING. It will show files starting with https if selected and not transfer it to the other structure.
Sheets("Main").Range("B4") = FoldersPath
End Sub
Sub Clear()
'Clears the URLs, the result column and the folder's path.
Dim LastRow As Long
'Find the last row.
With Sheets("Main")
.Activate
LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
End With
'Clear the ranges.
If LastRow > 7 Then
With Sheets("Main")
.Range("C8:D" & LastRow).ClearContents
.Range("B4:D4").ClearContents
.Range("B4").Select
End With
End If
End Sub
and the other part of the download macro is
'Check if the folder exists. I did not check whether it will also download with the https structure?
DownloadFolder = sh.Range("B4")
On Error Resume Next
If Dir(DownloadFolder, vbDirectory) = vbNullString Then
MsgBox "The path is incorrect!", vbCritical, "Folder's Path Error"
sh.Range("B4").Select
Exit Sub
End If
On Error GoTo 0
I tried with a script that I found on Stackoverflow but it does not work
I created an additional module:
Sub test()
Dim dm As New DriveMapper
Dim sharepointFolder As Scripting.Folder
Set sharepointFolder = dm.MapDrive("https://collaboration.company.corp/collrooms/")
' unsure whether I have to add something here and whether this will work with https
Debug.Print sharepointFolder.Path
End Sub
and added the following WebDAV mapping as a new CLASS
Option Explicit
Private oMappedDrive As Scripting.Drive
Private oFSO As New Scripting.FileSystemObject
Private oNetwork As New WshNetwork
Private Sub Class_Terminate()
UnmapDrive
End Sub
Public Function MapDrive(NetworkPath As String) As Scripting.Folder
Dim DriveLetter As String, i As Integer
UnmapDrive
For i = Asc("Z") To Asc("A") Step -1
DriveLetter = Chr(i)
If Not oFSO.DriveExists(DriveLetter) Then
oNetwork.MapNetworkDrive DriveLetter & ":", NetworkPath
Set oMappedDrive = oFSO.GetDrive(DriveLetter)
Set MapDrive = oMappedDrive.RootFolder
Exit For
End If
Next i
End Function
Private Sub UnmapDrive()
If Not oMappedDrive Is Nothing Then
If oMappedDrive.IsReady Then
oNetwork.RemoveNetworkDrive oMappedDrive.DriveLetter & ":"
End If
Set oMappedDrive = Nothing
End If
End Sub
The question is also whether removing the dispose method "Class_Terminate" which unmaps the drive would help? When the class goes out of scope then the drive get's unmapped. And how I could put it all together.
I'm experiencing some trouble with my VBA code. I have created an application in Excel and its copies have been distributed to users. To be able to correct bugs or add some new functions, every copy stores information what version it is. I have written procedure, that opens (read-only) a central file, that is providing some data a and information, which version is current. If the file, that opened this central file is older, it gets updated.
So the auto_open calls a procedure discovers that it has to be updated, saves the current file AS FileName_old.xlsm (to have some backup), kills the FileName.xlsm and copies a new file from a template. The problem is that the procedure crashes when it tries to kill the old file (to be more precise, it just ends without any error message). What confuses me is that when I run the auto_open macro manually (F5), everything goes correctly. Even step by step goes right. Also, when I call the update process via a button in a worksheet, it works perfectly. Any idea, what might cause this problem?
Thanks
Sub auto_open()
If Range("H_User").Value = "" Then UserNameWindows 'Write a user that is using this workbook in the range H_User
If Range("H_Updated").Value < FileDateTime(Range("H_File_Data").Value) Then UpdateData
End Sub
Sub UpdateData()
Dim ActWB As String
ActWB = ActiveWorkbook.Name
Application.ScreenUpdating = False
ThisWorkbook.Activate
If Not FileExists(Range("H_File_Data").Value) Then
MsgBox "The data file is not available!", vbCritical
Workbooks(ActWB).Activate
Application.ScreenUpdating = True
Exit Sub
End If
Dim WB As String, oknoData As String, IsTeam As Boolean, User As String
Dim version As Integer, Subversion As Integer, DataPath As String
On Error GoTo konec
Application.EnableCancelKey = xlDisabled
IsTeam = False
User = Range("H_User").Value
WB = ActiveWindow.Caption
version = Range("H_version").Value
Subversion = Range("H_Subversion").Value
Range("C_Data_All").ClearContents
DataPath = Range("H_File_Data").Value
Workbooks.Open fileName:=DataPath, ReadOnly:=True
oknoData = ActiveWindow.Caption
If Range("H_version_Spec").Value <= version Or (Range("H_version_Spec").Value = version And Range("H_Subversion_Spec").Value <= Subversion) Then
FileUpdate
End If
'If there is no need to update the file then continue with in this procedure
End Sub
Sub FileUpdate()
Dim NewPath As String, NewWB As String, OldPath As String, OldWB As String, BackupWB As String, BackupPath As String
Dim MainWB As String, version As String, Subversion As String
Dim versionMax As Integer, SubversionMax As Integer, versionMin As Integer, SubversionMin As Integer
ThisWorkbook.Activate
version = Range("H_version").Value
Subversion = Range("H_Subversion").Value
OldPath = ThisWorkbook.FullName
OldWB = ThisWorkbook.Name
BackupWB = Left(ThisWorkbook.Name, Len(ThisWorkbook.Name) - 5) & "_old.xlsm"
BackupPath = ThisWorkbook.Path & "\" & BackupWB
If Not FileExists(Workbooks(OldWB).Names("H_File_Data").RefersToRange.Value) Then
MsgBox "The data file is not available!", vbCritical
Exit Sub
End If
Workbooks.Open fileName:=Workbooks(OldWB).Names("H_File_Data").RefersToRange.Value, ReadOnly:=True
MainWB = ActiveWorkbook.Name
If version = Range("O_Spec_version").Value And Subversion >= Range("O_Spec_Subversion").Value Then
'Just some little piece of code if the version is not lower
Else
If FileExists(BackupPath) Then Kill (BackupPath)
If Not FileExists(Range("H_Path_Spec_Actual").Value) Then
MsgBox "The spec template is not available!", vbCritical
Exit Sub
End If
ThisWorkbook.SaveAs BackupPath
Kill (OldPath)
'Continue with update
End If
End Sub
Function FileExists(FilePath As String) As Boolean
Dim fso As Object
Set fso = CreateObject("scripting.filesystemobject")
FileExists= fso.FileExists(FilePath)
End Function
Option Explicit
Private Sub Workbook_Open()
Dim BackupPath As String
Dim OldPath As String
BackupPath = "folder\Filename_old.xlsm"
With ThisWorkbook
OldPath = .FullName
.SaveCopyAs BackupPath
.Saved = True
.ChangeFileAccess xlReadOnly
Kill .FullName
.Close False
End With
End Sub
The macro ,upon opening the workbook, will look to see if cell "C27" contains any of the following Text: Location1, Location2, Location3, or Location4. If they do then it will continue to save 2 copy files of the template by those locations. If not then it will open a UserForm To select the correct location from a ComboBox.
How could i reset the check after the UserForm is closed, I tried Call Auto_Open after the Unload me but it didnt work.
Macro
Sub Auto_Open()
With Range("B30")
.Value = Time
.NumberFormat = "h-mm-ss AM/PM"
End With
Dim FileName As String
Dim FilePath As String
Dim FileDate As String
Select Case Range("C27").Value
Case "Location1", "Location2", "Location3", "Location4"
FilePath = "C:\Users\aholiday\Desktop\FRF_Data_Macro_Insert_Test"
FileName = Sheets("Data").Range("C27").Text
Application.DisplayAlerts = False
ThisWorkbook.SaveAs FileName:=FilePath & "\" & FileName
Dim FileCopyName As String
Dim FileCopyPath As String
Dim FileTime As String
FilePath = "C:\Users\aholiday\Desktop\Backup"
FileName = Sheets("Data").Range("C27").Text
FileTime = Sheets("Data").Range("B30").Text
ThisWorkbook.SaveAs FileName:=FilePath & "\" & FileName & Space(1) & FileTime & ".xlsx", FileFormat:=xlOpenXMLWorkbook
MsgBox "File was saved! Ready for Next Test, Please Exit."
Case Else
MsgBox "File was not saved, Please Insert The Correct Testing Location"
UserForm.Show
Exit Sub
End Select
Application.DisplayAlerts = True
End Sub
UserForm
Private Sub UserForm_Initialize()
'Empty TestLocation Box
TestLocation.Clear
'Fill TestLocation Box
With TestLocation
.AddItem "Location1"
.AddItem "Location2"
.AddItem "Location3"
.AddItem "Location4"
End With
End Sub
'---------------------
Private Sub Insert_Click()
Sheets("Data").Activate
Range("C27").Value = TestLocation.Value
End Sub
'--------------------
Private Sub CloseBox_Click()
Unload Me
End Sub
By using the following code for the insert button:
Private Sub Insert_Click()
Sheets("Data").Range("C27").Value = TestLocation.Value
Auto_Open
End Sub
The code will work (tested it), as long as you have the Auto_Open code in a module.
If you put the Auto_Open sub in the ThisWorkbook then move it to the module.
Then use the following code in ThisWorkbook:
Private Sub Workbook_Open()
Auto_Open
End Sub
Also:
Case "Location1", "Location2", "Location1", "Location4"
Should be:
Case "Location1", "Location2", "Location3", "Location4"
Background : approx. 300 Excel surveys (with multiple sheets) should be centralized in 1 single excel.The macro is ready.
Goal : although the Macro is ready and able to copy the desired data from the Survey excel,I do not have the possibility to copy all 300 surveys at once ( I have to go 1 by 1 through all the surveys)
Question : is it possible to ask the macro to target copy from a specific network path and hereby to copy all the 300 excel workbooks?
Macro script :
Function bIsBookOpen(ByRef szBookName As String) As Boolean
On Error Resume Next
bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)
End Function
Sub Start()
currwb = ActiveWorkbook.Name
If bIsBookOpen("PERSONAL.XLSB") Then
Windows("PERSONAL.XLSB").Visible = True
ActiveWindow.Close
End If
If Workbooks.Count > 1 Then
MsgBox " To many files open... " & Workbooks(1).Name
Else
Application.Dialogs(xlDialogOpen).Show
Response = MsgBox("Weiter mit 'IT-Personal'?", vbYesNo)
If Response = vbYes Then
Windows(currwb).Activate
Call CopyForm
End If
End If
End Sub
To loop through files in a folder,
Sub LoopThroughFiles()
Dim path As String
Dim filename As String
Dim wb As Workbook
path = "" 'your folder path here
filename = Dir(path & "*.xls")
While (filename <> "")
Set wb = Workbooks.Open(path & filename)
'Your code goes here
wb.Close
filename = Dir
Wend
End Sub