VBA fails on first try error 5479 - vba

It seems like this guy has had the same problem as me, but the vbModeless doesn't seem to do the trick.
I'm creating a simple add-in, and I want VBA to open a word file, copy the entire content and paste it in the original document.
It works perfectly when executed from the VBA editor or even after the first run where it debugs, but opening a Word instance for the first time and trying to execute the code from the add-in seems to be a problem.
The code is as follows:
Sub insertFigureFrame(control As IRibbonControl)
StandardFrames.StartUpPosition = 0
StandardFrames.Top = Application.Top + (Application.Height - StandardFrames.Height) * 0.5
StandardFrames.Left = Application.Left + (Application.Width - StandardFrames.Width) * 0.5
StandardFrames.Show
End Sub
Sub Standard()
Dim OriginalDocument As String
Dim SaveChanges As Boolean
Dim doc As Document
On Error GoTo err:
Application.DisplayAlerts = wdAlertsNone
Application.ScreenUpdating = False
OriginalDocument = ActiveDocument.Path
Documents.Open MyTemplate
Selection.WholeStory
Selection.Copy
Documents("MyTemplate").Close (SaveChanges = False)
Documents.Open (OriginalDocument)
Selection.PasteAndFormat wdPasteDefault
Exit Sub
err:
Call errHandling
End Sub
The StandardFrames Userform calls the sub Standard.
Any idea what might cause the problem?
EDIT:
I'm using Word 2007 and Windows XP.

Try hidding your userform before you open a document:
Sub Standard()
StandardFrames.Hide
'The rest of your code
End Sub

Related

Word VBA delete hidden bookmarks before closing

I want to set up a VBA so that for any document based on a template hidden bookmarks are deleted prior to the document closing. We publish documents on our website. They are written as Word and an API converts them to html. If there are hidden bookmarks they appear as links on the website (the hidden bookmarks convert to html anchors). Currently we remove the bookmarks manual prior to the API, but this is time consuming (we publish 1000s of documents a year) and ineffective (people forget).
I found VBA to remove hidden bookmarks which works and tried to add DocumentBeforeClose as the trigger. But it doesn't work:
Private Sub DocumentBeforeClose(cancel As Boolean)
Dim nBK As Long
With ActiveDocument
For nBK = .Bookmarks.Count To 1 Step -1
If LCase(Left(.Bookmarks(nBK).Name, 3)) = "_hl" Then
.Bookmarks(nBK).Delete
End If
Next nBK
End With
ActiveDocument.Save
End Sub
I went through Visual Basic Window, Normal, Microsoft Word Objects, ThisDocument.
Nothing happens, the hidden bookmarks remain if I close and re-open the document.
I think you need to add this line :
.Bookmarks.ShowHidden = True
Like this it should work :
Private Sub DocumentBeforeClose(cancel As Boolean)
Dim nBK As Long
With ActiveDocument
.Bookmarks.ShowHidden = True
For nBK = .Bookmarks.Count To 1 Step -1
If LCase(Left(.Bookmarks(nBK).Name, 3)) = "_hl" Then
.Bookmarks(nBK).Delete
End If
Next nBK
End With
ActiveDocument.Save
End Sub
This has solved it:
Sub AutoClose()
On Error Resume Next
Dim nBK As Long
With ActiveDocument
.bookmarks.ShowHidden = True
For nBK = .bookmarks.Count To 1 Step -1
If LCase(Left(.bookmarks(nBK).Name, 3)) = "_hl" Then
.bookmarks(nBK).Delete
End If
Next nBK
End With
ActiveDocument.Save
End Sub
Only issue is that it tries to run when you open a document and puts up an error message that there is no active document. 'On error resume next' is to stop that error message

In Word 2010 use VBA to make first document to fit page

When Word 2010 starts I would to automatically execute the VBA code
ActiveWindow.ActivePane.View.Zoom.PageFit = wdPageFitFullPage
to make the document fit the page.
Many thanks for a tip
You can put your command(s) in the AutoExec macro.
Sub AutoExec()
ActiveWindow.ActivePane.View.Zoom.PageFit = wdPageFitFullPage
End Sub
You could add a macro like the following to the 'ThisDocument' code module of a global template (e.g. Normal.dotm):
Private Sub Document_Open()
With ActiveWindow
'Reduce flickering while changing settings
.Visible = False
'Switch to a single view pane
.View.SplitSpecial = wdPaneNone
.View.Type = wdPrintView
.ActivePane.View.Zoom.PageFit = wdPageFitFullPage
'Restore the window now that we're finished
.Visible = True
End With
End Sub

Why does Excel vba copy to clipboard inconsistently?

I have an excel macro that does two very simple things:
It displays the current date and time in a little window.
It copies the display as a text string for pasting into other apps as needed.
The cell that is displayed has the following formula in it:
=TEXT(NOW(),"yyyy.MM.dd hh:mm:ss")
Every 5 seconds, the macro refreshes the time and the clock ticks.
My problem is that when I copy the time from the cell, I don't consistently get the contents pasted to the clipboard. Sometimes the cell contents are posted to the clipboard. I can't figure out why it works sometimes and not others as there isn't a lot going on. It should just always work.
I know the data aren't on the clipboard because I can try pasting the clipboard into different programs like notepad and other text apps and nothing happens.
The entire code is in a single module.
Dim stopSwitch As Integer
Dim NextTick
Sub myupdate()
If ActiveCell.Address = "$B$1" Then
growWindow ' resize window beyond just clock display
stopTime '
Exit Sub ' stop updating
End If
Range("a1").Select
Calculate
DoEvents
If ActiveWorkbook.Name = "calendar clock.xlsb" Then shrinkWindow
NextTick = Now + TimeValue("00:00:05") ' give me 5 seconds to copy/paste
Application.OnTime NextTick, "myupdate"
ThisWorkbook.Save ' futile attempt to prevent save dialog
End Sub
Sub auto_open()
' to stop clock, tap right arrow to select cell b1 when workbook is active
Range("a1").Select
myupdate
End Sub
Sub growWindow()
Application.Width = 768
Application.Height = 621.75
ThisWorkbook.Save
End Sub
Sub shrinkWindow()
' strip decorations so window is as small as possible
Application.DisplayFormulaBar = False
ActiveWindow.DisplayGridlines = False
ActiveWindow.DisplayHeadings = False
' move window to second monitor and size to single cell display
Application.WindowState = xlNormal
Application.Top = 0
Application.Left = -720
Application.Width = 174
Application.Height = 127
ActiveWindow.WindowState = xlMaximized
End Sub
Sub stopTime() ' called when workbook is closed
On Error Resume Next
Application.OnTime NextTick, "myupdate", schedule:=False
Range("b1").Select
End Sub
Sub copyTime()
Range("a1").Copy ' copy time
Range("f5").PasteSpecial xlPasteValues ' strip formatting
Range("f5").Copy ' copy time as text
DoEvents ' hack to attempt to make copy work consistently
End Sub
The above code sizes the window and updates the clock every 5 seconds.
To copy the clock as text to the clipboard, I have the following code in the workbook
Private Sub Workbook_Activate()
Application.OnKey "^c", "module1.copyTime"
End Sub
Private Sub Workbook_Deactivate()
Application.OnKey "^c"
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
' turn off auto update
Module1.stopTime
' resize window so if I open another spreadsheet, it's a reasonable size
Application.WindowState = xlNormal
Application.Width = 768
Application.Height = 621.75
Application.OnKey "^c"
ThisWorkbook.Save ' try to prevent save dialog at close
End Sub
I modified the copyTime function to verify the ^C is seen by selecting the unformatted cell and I can see that the data consistently go to the cell so I know my problem isn't with the Range("a1").copy step in copytime or the pastespecial to cell f5.
That leaves the range("a5").copy command as the bad actor when the copy fails which is weird. It's as if copy works as long as the data are kept inside the spreadsheet but fails to update the external clipboard consistently.
That observation led me to try setting application.cutcopymode to xlcopy, true and false to see if that helped. The only effect I saw from trying all the settings is whether I saw f5 get highlighted with a marquee or not - none of the setting forced a copy to the external clipboard.
I tried waiting for a clock tick before copying to see if something was clearing the clipboard following the copy if it was time to update the clock. That appeared to help somewhat but, again not consistently.
So why does the copy fail to always update the clipboard? And why does it not work when it doesn't and does when it does? Even better, how can I modify this code so it always exports to the external clipboard?
Try using this method, it's always reliable for me
Dim TimeInClip As MSForms.DataObject
Set TimeInClip = New MSForms.DataObject
TimeInClip.SetText Range("A1").Value
TimeInClip.PutInClipboard
Try
Sub copyTime()
Range("a1").Copy ' copy time
Range("f5").PasteSpecial xlPasteValues ' strip formatting
Application.CutCopyMode = False ' Clear Excel clipboard
Range("f5").Copy ' copy time as text
DoEvents ' hack to attempt to make copy work consistently
End Sub
You said that you tried Application.CutCopyMode, but have you tried it that way?
It only forces the application to clear the clipboard before copying something else, which should then copy properly on the fresh clipboard.

Word Macro - these steps work in separate macros, but not together

This switches Microsoft Word 2013 to the Home Tab:
Sub HomeTab()
Application.ScreenUpdating = False
SendKeys "%h%"
ScreenUpdating = True
End Sub
This opens a document:
Sub OpenToDoLIst()
Documents.Open FileName:="C:\Users\Name\Name Documents\Microsoft Word Documents\Work Menu\To Do List.doc"
End Sub
But if I combine the two like this:
Sub WorkOpenToDoList()
Application.ScreenUpdating = False
SendKeys "%h%"
ScreenUpdating = True
Documents.Open FileName:="C:\Users\Name\Name Documents\Microsoft Word Documents\Work Menu\To Do List.doc"
End Sub
It doesn’t switch the original document I started from when I activated the macro to the Home Tab, it only opens the document. I suspect it's not waiting for the HomeTab steps to finish in the original window, but I don't know why.

Refreshing Data Connections in Excel 2010 VBA

So I have all of my VBA code down and it seems to be right, but it just is not refreshing the workbooks. The only thing that I can think of is when I open up the sheets I have to enable editting, so would I need to add something to my code?
Edit: I am running this through a VBScript
Public wb As Workbook
Sub executeUpdate()
`some code
openBook path & testArray(i) & ext, True
saveBookAs path & testArray(i)
End Sub
Sub openBook(ByVal fileName As String, ByVal refresh As Boolean)
Set wb = Workbooks.Open(fileName, 0, False)
If refresh = True Then
wb.RefreshAll
End If
End Sub
Sub saveBookAs(ByVal fName As String)
wb.SaveAs fileName:=fName & "_posReport.xlsx"
End Sub
I found this code over here:
If Application.ProtectedViewWindows.Count > 0 Then
Application.ActiveProtectedViewWindow.Edit
End If
Have not tested it, but maybe it works for you.
--
Quote:
code will bypass the need for the user to select the "Enable Editing" button on the message bar below the ribbon. One additional note [...] the code will error if the workbook isn't in "ProtectedView". So to avoid this the following code will only enable editing if the workbook has "ProtectedView" enabled.