I have been trying to automatically refresh my table (obtained from an SQL database via power query) and directly save it as a text file (tab delimited)
I'm very new with VBA and the macro i used is
Public Sub UpdatePowerQueries()
'Macro to update the Power Query script(s) and save the file as .txt
Dim cn As WorkbookConnection
For Each cn In ThisWorkbook.Connections
If Left(cn, 13) = "Power Query -" Then cn.Refresh
Next cn
Application.DisplayAlerts = False
ActiveSheet.SaveAs Filename:="customfile" & Format(Date, "yyyymmdd") & ".txt", FileFormat:=xlTextWindows
Application.DisplayAlerts = True
End Sub
now the issue I've been facing is that the refresh part and the save part work ok on their own, but if I put them in the same macro, the save part happens too soon, and the text file is empty. Can anyone help me ?
Thanks
Personnaly, I have choose to be a bit patient and added a timer to go on after a few seconds!
Try to add this in between :
DoEvents
Application.Wait (Now + TimeValue("0:00:05"))
DoEvents
Related
I have an excel workbook (which is updated daily) to which I have established a couple power query connections, they look like this:
IMG
When clicking the little button to update the connection it works fine, updates, new lines are added, changes in data happen. I've then set out to execute this update through VBA in an automatic fashion when the data source files finishes being worked on and is closed (In a manner that would make opening the file with the queries and manually updating them unnecessary), following are examples of what I've tried(All using the "Workbook_BeforeClose" event):
Method 1 (Unsuccessful):
Sub Workbook_BeforeClose(cancel As Boolean)
CarryOn = MsgBox("Update connections? (May take a minute)", vbYesNo, "Update connections")
If CarryOn = vbYes Then
Dim strFilename As String: strFilename = "R:\filepath\Querydestination.xlsm"
Dim QD As Workbook 'QD = Query Destination
Set QD = Workbooks.Open(Filename:=strFilename)
QD.RefreshAll
QD.Connections("Query - Database").Refresh
QD.Connections("Query - Support$_FilterDatabase").Refresh
QD.Save
QD.Close
ThisWorkbook.Save
Beep
MsgBox "Connections updated!"
End If
End Sub
I've since found the code from the first answer of the following post:
Auto-updating Power Query Connection via VBA
The code currently looks like this:
Sub Workbook_BeforeClose(cancel As Boolean)
CarryOn = MsgBox("Update connections? (May take a minute)", vbYesNo, "Update connections")
If CarryOn = vbYes Then
Application.DisplayAlerts = False
ThisWorkbook.SaveAs Filename:= _
"R:\filepath\Database.xlsb" _
, FileFormat:=50
Dim strFilename As String: strFilename = "R:\filepath\Querydestination.xlsm"
Dim QD As Workbook 'QD = Query Destination
Set QD = Workbooks.Open(Filename:=strFilename)
Dim con As WorkbookConnection
Dim Cname As String
For Each con In ActiveWorkbook.Connections
If Left(con.Name, 8) = "Query - " Then
Cname = con.Name
With ActiveWorkbook.Connections(Cname).OLEDBConnection
.BackgroundQuery = False
.Refresh
End With
End If
Next
QD.Save
QD.Close
ThisWorkbook.Save
Beep
MsgBox "Connections updated!"
Application.DisplayAlerts = True
End If
End Sub
Here's the problem: I've tried Refresh_all, Update connections, Updtade individual connection by name and a bunch of other stuff, only the method in the link and shown in the code above has worked. Sometimes it hiccups in the .Refresh line but thats it. I works on my machine, when opening the Query Destination file new lines and changes are there, without the need to manually open the file and hit the "Refresh" or "Refresh all" buttons.
The only matter is: the code runs smoothly sometimes, but sometimes it doesn't and throws an error: [IMG] [IMG].
I really don't know what is causing it, the queries destination workbook is not open and nobody is using it, I've made sure of that. How to stop this error from occuring?
I've tried to use the below code which I found on this conversation How To Search And Replace Across Multiple Files In Word? supplied by Charles Kenyon. However, it doesn't seem to work for me. I've enabled macros on my word and added the below code as a new module in Macros. When I go to replace all, it'll replace the text as per normal, but after doing this, when I open up the other macros enabled word doc, I find that the same text is still in these docs, without being replaced. Am I doing something wrong? Namely, I also wish to add a wildcard entry into my replace all, will the below code work or can someone suggest a better alternative? I have tested the below code with and without wildcard entries to no avail. I've also tried the code on this page in my macros but it also didn't work How to find and replace a text in multiple Word documents using VBAThanks for any help!
Option Explicit
Public Sub BatchReplaceAll()
Dim FirstLoop As Boolean
Dim myFile As String
Dim PathToUse As String
Dim myDoc As Document
Dim Response As Long
PathToUse = "C:\Test\"
'Error handler to handle error generated whenever
'the FindReplace dialog is closed
On Error Resume Next
'Close all open documents before beginning
Documents.Close SaveChanges:=wdPromptToSaveChanges
'Boolean expression to test whether first loop
'This is used so that the FindReplace dialog will
'only be displayed for the first document
FirstLoop = True
'Set the directory and type of file to batch process
myFile = Dir$(PathToUse & "*.doc")
While myFile <> ""
'Open document
Set myDoc = Documents.Open(PathToUse & myFile)
If FirstLoop Then
'Display dialog on first loop only
Dialogs(wdDialogEditReplace).Show
FirstLoop = False
Response = MsgBox("Do you want to process " & _
"the rest of the files in this folder", vbYesNo)
If Response = vbNo Then Exit Sub
Else
'On subsequent loops (files), a ReplaceAll is
'executed with the original settings and without
'displaying the dialog box again
With Dialogs(wdDialogEditReplace)
.ReplaceAll = 1
.Execute
End With
End If
'Close the modified document after saving changes
myDoc.Close SaveChanges:=wdSaveChanges
'Next file in folder
myFile = Dir$()
Wend
End Sub
I want to generate an automatic footer when I save a new MS Word file, and update the footer if I SaveAs the file.
The code below used to work well with an old Word. With the latest Word it only works if I press F12 on the keyboard. Any help would be greatly appreciated!
Sub FileSaveAs()
Dialogs(wdDialogFileSaveAs).Show
Dim i As Long
Dim ThisPath As String
Dim pName As String
Dim TextInFooter As String
Dim FullName As String
ThisPath = ActiveDocument.Path
pName = ActiveDocument.Name
FullName = ThisPath & "\" & pName
TextInFooter = "This file was saved in: " & FullName & " on the " & Now
For i = 1 To ActiveDocument.Sections.Count
With ActiveDocument.Sections(i)
.Footers(wdHeaderFooterPrimary).Range.Text = TextInFooter
End With
Next
End Sub
As you noticed, the new version triggers the FileSaveAs only on F12. Not sure if this is bug or a feature.
If it is only important that the document shows the information in print or on open - my suggested workaround:
You could avoid the insertion into the footer on save and insert it using fields, the document already has the information you are inserting. You simply need to make it visible. The footer would be then:
This file was saved as { FILENAME \p } the { SAVEDATE \# "dd.MM.yyyy HH:mm:ss"}
Adjust the Date/Time format as needed. You have to force the update of the fields - this is where the auto macros come into it.
Sub AutoOpen()
' set fields to update before printing (if saved as and printed while open)
Options.UpdateFieldsAtPrint = True
' Update all current fields in just opened document
ActiveDocument.Fields.Update
End Sub
Sub AutoClose()
' update fields when closing
ActiveDocument.Fields.Update
End Sub
The only difference would be, that you have the full path including file name and extension there. Additionally, there might be times, when the file is saved but not yet opened/closed/printed and has also not updated the fields.
In theory, you could insert the footer into the document with the AutoOpen macro as well (activedocument.fields.add).
I'm trying to add a few custom document properties to a folder of word documents.
I know that the loop itself works fine, because I used the same loop with different code to modify and then update pre-existing custom document properties.
The code to add custom document properties also works, I tested it by running it in it's own macro for a single document, which worked fine.
Since the loop works and the code within the loop also works, I just can't figure out what's wrong with it.
Here's the code:
Sub add_custom_docproperties()
Dim file
Dim path As String
Dim filepath As Variant
filepath = InputBox("Please enter the filepath for the files you want to
update.", "Input Filepath", "Copy filepath here...")
Select Case StrPtr(response)
Case 0
endednotification = MsgBox("The macro has been ended.", , "Notification")
Exit Sub
Case Else
End Select
path = filepath & "\"
file = Dir(path & "*.*")
'Application.ScreenUpdating = False
Do While file <> ""
Documents.Open FileName:=path & file
Check = MsgBox(path & file, , "Check")
ActiveDocument.CustomDocumentProperties.Add Name:="firstdocprop",
_LinkToContent:=False, Type:=msoPropertyTypeString, Value:="The First One"
ActiveDocument.CustomDocumentProperties.Add Name:="seconddocprop",
_LinkToContent:=False, Type:=msoPropertyTypeString, Value:="Second"
ActiveDocument.CustomDocumentProperties.Add Name:="thirddocprop",
_LinkToContent:=False, Type:=msoPropertyTypeString, Value:="Third"
'original example from:
'https://msdn.microsoft.com/en-us/vba/office-shared-vba
/articles/documentproperties-add-method-office
ActiveDocument.Save
ActiveDocument.Close
'set file to next in Dir
file = Dir()
Loop
'Application.ScreenUpdating = True
MsgBox "The macro is complete."
End Sub
As you can see I have a comment there with the first example I tried from msdn, which I modified.
Thanks in advance for any help, even if you could just point me to a resource explaining where I've gone wrong or something like that.
Word does not recognise the changes to the CustomDocumentProperties as being sufficiently important to actually save the document when you execute the Save command - unless you had made other changes it just decides to ignore the Save.
You can force a save by telling Word that the document has not been saved since it was last changed:
ActiveDocument.Saved = False
ActiveDocument.Save
ActiveDocument.Close
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.