I'm trying to create a VBA code to do this:
Open a dialog box to choose a word file in the path: C:\Add-in\Company A\Templates in docx format
Select as active sheet Navette the file: "Checklist - Navette" if there's no open file with this name appear a message: "ERROR Please push the comand checklist first" and quit the macro
Populate all the bookmarks of the word file with content cells that have name equal as the bookmarks (use sheet Navette)
If the Navette sheet has a cell named "Civilité" and the content is equal to "Female" must go to the excel file in the path: C:\Add-in\Mapping.xlsx on the Replace sheet and search all the words in the column A throught the word file and replace with words in the column B otherwise replace with the words in the column C
Open a dialog box to input the path to save the word with the name TEST in word and pdf format
Close the initial files without saving
Quit all aplications
I'm stucked in the code and it's even working. When I try to run It also get stucked :(
Sub TestProcess()
'Initial process
Dim fd As FileDialog
Dim strFile As String
Dim wdDoc As Document
Dim wb As Workbook
Dim ws As Worksheet
Dim rng As Range
Dim SaveAsFileName As String
Dim SaveAsFileFormat As Integer
'Dialog box to pickup the docx file
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.InitialFileName = "C:\Add-in\Company\Templates"
.Filters.Add "Word Files", "*.docx", 1
If .Show = -1 Then
strFile = .SelectedItems(1)
End If
End With
Set wdDoc = Documents.Open(strFile)
'Identify the checklist
On Error Resume Next
Set wb = Workbooks("Company - Navette.xlsx")
On Error GoTo 0
'Handling with errors
If wb Is Nothing Then
MsgBox "ERROR 'Please select the command *Open Navette*first"
wdDoc.Close
Set wdDoc = Nothing
Exit Sub
End If
'Active Worksheet
On Error Resume Next
Set ws = wb.Sheets("Navette")
On Error GoTo 0
'Handling with errors
If ws Is Nothing Then
MsgBox "Sheet 'Navette' not found in the workbook."
'For each Bookmark equal name cell replace with the content
For Each wdBookmark In wdDoc.Bookmarks
wdBookmark.Range.Text = ws.Range(wdBookmark.Name).Value
Next
'Save file
'Open a dialog box to input the path to save the Word file
SaveAsFileName = Application.GetSaveAsFilename(FileFilter:="Word Files (*.docx), .docx; PDF Files (.pdf), *.pdf", Title:="Save As", InitialFileName:=strFile)
'Check if a file name and format are selected
If SaveAsFileName <> "False" Then
'Determine the selected file format
If Right(SaveAsFileName, 4) = ".pdf" Then
SaveAsFileFormat = 17
Else
SaveAsFileFormat = 0
End If
'Save the file in the selected format
objDoc.SaveAs SaveAsFileName, FileFormat:=SaveAsFileFormat
End If
'Close Doc & Excel
wdDoc.Close
wb.Close
'Reset the documents
Set wdDoc = Nothing
Set wb = Nothing
Exit Sub
End If
End Sub
Related
I have a lot of files in one folder. What I want to do is add a column with the name of the file. I found a solution to this, but I want to optimize. Currently I am just adding the values from J2 to J1000 to make sure I cover all rows. This is not ideal as the amount of rows in each file differ. What I want to do is find a way to add the value matching the amount of rows that exists in the sheet.
I want to find a way to check if there is data in column A for each row and then add the value as long as there is some data in column A for each row.
My thoughts would be to do a while statement to check if each row in column A is different from an empty string and add the value as long as it is different from an empty string. However I am not sure how to implement this.
Here is my code:
Sub AllWorkbooks()
Dim MyFolder As String 'Path collected from the folder picker dialog
Dim MyFile As String 'Filename obtained by DIR function
Dim wbk As Workbook 'Used to loop through each workbook
On Error Resume Next
Application.ScreenUpdating = False
'Opens the folder picker dialog to allow user selection
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder"
.Show
.AllowMultiSelect = False
If .SelectedItems.Count = 0 Then 'If no folder is selected, abort
MsgBox "You did not select a folder"
Exit Sub
End If
MyFolder = .SelectedItems(1) & "\" 'Assign selected folder to MyFolder
End With
MyFile = Dir(MyFolder) 'DIR gets the first file of the folder
'Loop through all files in a folder until DIR cannot find anymore
Do While MyFile <> ""
'Opens the file and assigns to the wbk variable for future use
Set wbk = Workbooks.Open(FileName:=MyFolder & MyFile)
'Replace the line below with the statements you would want your macro to perform
Sheets(1).Range("j1").Value = "Date"
Sheets(1).Range("j2:j1000").Value = Mid(ActiveWorkbook.Name, 10, 10)
wbk.Close savechanges:=True
MyFile = Dir 'DIR gets the next file in the folder
Loop
Application.ScreenUpdating = True
End Sub
I have three files. One excel file that is empty and contains my Macro. Second excel file that has about 20 tabs with updated data (Variable "UpdatedFiles" contains the file path) that needs to by copy/pasted into my third excel file (Variable "ProvisionFiles" contains the file path), that has extra tabs that link to the tabs that I am copy/pasting in.
My code works great right up to the point that I hit the Copy/Paste Section of my For Each Loop. Note that the tabs that I am copying over have the overlapping/same tab names in both workbooks.
I have tried to copy/paste data with all three methods described in this video. https://www.excelcampus.com/vba/copy-paste-cells-vba-macros/
Still can't get it to work.
`Sub CopyPasteData()
Dim ProvisionFile As String 'String File Path of Provision File
Dim UpdatedFile As String 'String File Path of Updated OneSource Files
Dim ws As Worksheet 'Used to Loop Though WS Tabs in Updated OneSource Files
Dim wsName As String 'Name of Tab of OneSource File
Dim lastRow As Long
Dim lastColumn As Long
'Open Dialog Box that allows you to Select the Provision File
MsgBox "Select your provision file, which is the destination for the updated OneSource Reports. Please ensure this file is closed before opening."
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Title = "Select file"
.InitialFileName = "C:\"
If .Show = -1 Then
'ok clicked
ProvisionFile = .SelectedItems(1)
Workbooks.Open(ProvisionFile).Activate
'Worksheets("Control").Activate
Else
'cancel clicked
End If
End With
'Get updated Reports
MsgBox "Select the file that contains the updated OneSource Reports."
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Title = "Select file"
.InitialFileName = "C:\"
If .Show = -1 Then
'ok clicked
UpdatedFile = .SelectedItems(1)
Workbooks.Open(UpdatedFile).Activate
Else
'cancel clicked
End If
End With
'Loop through Each tab in Updated File
For Each ws In Worksheets
wsName = ws.Name
lastRow = Sheets(wsName).Cells(Rows.Count, 1).End(xlUp).Row
lastColumn = Sheets(wsName).Cells(7, Columns.Count).End(xlToLeft).Column
'Debug.Print ("Yes")
Workbooks(ProvisionFile).Worksheets(wsName).Range(Workbooks(ProvisionFile).Worksheets(wsName).Cells(1, 1), Workbooks(ProvisionFile).Worksheets(wsName).Cells(lastRow, lastColumn)) = Sheets(wsName).Range(Sheets(wsName).Cells(1, 1), Sheets(wsName).Cells(lastRow, lastColumn))
Next ws
End Sub`
Expected result is to finish the copy/paste loop.
Error I am recieving = Run-time error'9': Subscript out of range
Source column contains a string in each cell. There are 4000+ cells. These need to be copied and pasted into a worksheet of the active (one that invoked the macro) workbook. Source workbook should be selected by the user using a search/browse pop-up box.
The below code does something close to my intended goal, but the directory as you see is static which is unacceptable. Maximum flexibility should be had with user choosing the source file manually. Furthermore I want to prevent the file path from becoming obsolete every time folders/files get renamed/shifted. Something tell me Application.GetOpenFilename() should be used, but how to correctly implement it?
Having little experience with the VBA, my attempts to mod this macro failed, so I'm asking for your advice on this matter. Again, the below code works well, but it's not flexible enough to be practical.
Edit: the problem is solved. See the final working code.
'MACRO TO READ-IN EXTERNAL EXCEL FILE FROM WHICH JOB NO.'S ARE EXTRACTED INTO USERFORM
Sub ReadDataFromCloseFile()
'IN CASE OF ERROR SEND TO ERROR FUNCTION
On Error GoTo ErrHandler
'PREVENT OPENED EXCEL SOURCE FILE FROM SHOWING TO USER
Application.ScreenUpdating = False
'OPEN SOURCE EXCEL WORKBOOK IN "READ ONLY MODE"
Dim SrcName As String
Dim src As Workbook
SrcName = Application.GetOpenFilename()
Set src = Workbooks.Open(SrcName, True, True)
'GET THE TOTAL ROWS FROM THE SOURCE WORKBOOK
Dim iTotalRows As Integer
iTotalRows = src.Worksheets("PROJECT LIST").Range("A1:A" & Cells(Rows.Count, "A").End(xlUp).Row).Rows.Count
'COPY DATA FROM SOURCE WORKBOOK -> DESTINATION WORKBOOK
Dim iCnt As Integer '(COUNTER)
For iCnt = 1 To iTotalRows
Worksheets("Test_File_8").Range("B" & (iCnt + 1)).Formula = src.Worksheets("PROJECT LIST").Range("A" & (iCnt + 1)).Formula
Next iCnt
'CLOSE THE SOURCE WORKBOOK FILE
src.Close False 'FALSE = DONT SAVE THE SOURCE FILE
Set src = Nothing 'FLUSH DATA
'ERROR FUNCTION
ErrHandler:
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
See my changes below. I added two variables X and strSrc. X is a variant that is used to loop through .SelectedItems and strSrc is that string that ultimately holds the path.
Sub ReadDataFromCloseFile()
'Set variable to hold workbook path and workbook path string
Dim X as Variant
Dim strSrc as String
With Application.FileDialog(msoFileDialogFilePicker)
.InitialFileName = "" ' You can provide a base path here
.Title = "Select file."
.AllowMultiSelect = False
If .Show = -1 Then
For Each X In .SelectedItems
strSrc = X
Exit For
Next X
End If
End With
'IN CASE OF ERROR SEND TO ERROR FUNCTION
'On Error GoTo ErrHandler
'PREVENT OPENED EXCEL SOURCE FILE FROM SHOWING TO USER
Application.ScreenUpdating = False
'OPEN SOURCE EXCEL WORKBOOK IN "READ ONLY MODE"
Dim src As Workbook
Set src = Workbooks.Open(strSrc, True, True)
'GET THE TOTAL ROWS FROM THE SOURCE WORKBOOK
Dim iTotalRows As Integer
iTotalRows = src.Worksheets("PROJECT LIST").Range("A1:A" & src.Worksheets("PROJECT LIST").Cells(Rows.Count, "A").End(xlUp).Row).Rows.Count
'COPY DATA FROM SOURCE WORKBOOK -> DESTINATION WORKBOOK
Dim iCnt As Integer '(COUNTER)
For iCnt = 1 To iTotalRows
src.Worksheets("Test_File_8").Range("B" & (iCnt + 1)).Formula = src.Worksheets("PROJECT LIST").Range("A" & (iCnt + 1)).Formula
Next iCnt
'CLOSE THE SOURCE WORKBOOK FILE
src.Close False 'FALSE = DONT SAVE THE SOURCE FILE
Set src = Nothing 'FLUSH DATA
'ERROR FUNCTION
ErrHandler: Application.EnableEvents = True Application.ScreenUpdating = True End Sub
'MACRO TO READ-IN EXTERNAL EXCEL FILE FROM WHICH JOB NO.'S ARE EXTRACTED INTO USERFORM
I'm looking to open multiple Excel files and run the same macro (contained in each) on each file.
For example, I'd like to automatically open every file in h:\dbs and execute the CmdUpdate_Click macro within each file.
How might I go about this?
Try something like this. I expect you can research how to open the Visual Basic Editor and figure out where to paste this.
'Declare variables
Dim FolderObj, FSO, FileObj As Object
Dim FolderDialog As FileDialog
'Create and run dialog box object
Set FolderDialog = Application.FileDialog(msoFileDialogFolderPicker)
With FolderDialog
.ButtonName = "Select"
.AllowMultiSelect = False
.InitialFileName = "B:\BIM Projects\"
.InitialView = msoFileDialogViewDetails
'Check if user canceled dialog box
'Exit if yes
If .Show = -1 Then
MsgBox "No Folder Selected"
Exit Sub
End If
End With
'Check if user canceled dialog box
'Exit if yes
'Create a File System Object to be the folder that was selected
Set FSO = CreateObject("scripting.filesystemobject")
Set FolderObj = FSO.getfolder(FolderLocation)
'For each obj in the selected folder
For Each FileObj In FolderObj.Files
'Test if the file extension contains "xl" and make sure it's an Excel file before opening
If InStr(1, Right(FileObj.Name, Len(FileObj.Name) - InStr(1, FileObj.Name, ".")), "xl") = 1 Then
'Prevent the workbook from displaying
ActiveWindow.Visible = False
'Open the Workbook
Workbooks.Open (FolderObj & "\" & FileObj.Name)
'Run the Macro
Application.Run "'" & FolderObj & "\" & FileObj.Name & "'!CmdUpdate_Click"
'Save the Workbook
Workbooks(FileObj.Name).Save
'Close the Workbook
Workbooks(FileObj.Name.Close
End If
'Turn this back on
ActiveWindow.Visible = True
Next
I will caution you that this is based on some code I wrote for Word, so there are no guarantees it will work and I don't have time to test it. It will, however, give you a very good start if it doesn't.
Edit to Add: You may
It is supposed to open the file, save as, copy values, Save as again (final filename), then to delete the first save as. I am using this to achieve a temporary .xlsx file. It works, opens, saves as window comes up, then deletes the Temp file but it is not saving the file before it deletes the temp file.
Code:
Sub PracticeMakesPerfect()
Dim wbMain As Workbook
Dim Alpha As Workbook
Dim Beta As Workbook
Dim sFile As String
Dim PurgeTemp
Application.DisplayAlerts = False
Set wbMain = Workbooks("Macro Tester.xlsm")
Set Alpha = Workbooks.Open("C:\Users\frfcomputer\Desktop\Test.xlsx")
ActiveWorkbook.SaveAs "C:\Users\frfcomputer\Desktop\test\Temp.xlsx"
Set Beta = Workbooks("Temp.xlsx")
wbMain.Sheets("Sheet1").Range("A1").Value = Beta.Sheets("Sheet1").Range("A1").Value
Application.DisplayAlerts = True
Application.GetSaveAsFilename
ActiveWorkbook.Close
'Source File Location
sFile = "C:\Users\frfcomputer\Desktop\test\" & "Temp.xlsx"
'Sets Object
Set PurgeTemp = CreateObject("Scripting.FileSystemObject")
'Checks File Exists or Not
If PurgeTemp.FileExists(sFile) Then
'If file exists, delete the file
PurgeTemp.DeleteFile sFile, True
MsgBox "Deleted The File Successfully", vbInformation, "Done!"
Else
'If file does not exists
MsgBox "Specified File Not Found", vbInformation, "Not Found!"
End If
End Sub
You're asking for a filename to save as with Application.GetSaveAsFilename but you're not putting it to use:
Sub test()
Dim a As String
a = Application.GetSaveAsFilename(FileFilter:="Excel Files, *.xls") 'Ask for a filename to save as.
ThisWorkbook.SaveAs a 'Save the file
End Sub
It's the end of the day, so haven't added everything - check that the result of a isn't FALSE or some other unusable name. There's also various options available under SaveAs.