I am trying to run a macro from excel that will open up an existing word document, populate the fields from excel to word via content controls, and paste/format a table into the word document at a certain location. About 20% of the time, I'll get this Run Time Error 462 stating "The remote Server Machine Does Not Exist or is Unavailable". I will provide the code and the section where is usually gets stuck at as everything after works 100% of the time. Please help on this.
Public Sub Agreement()
With Sheets("Price List Table")
.ListObjects(1).Name = "Table1"
End With
Dim tbl As Excel.Range
Dim wrdApp
Dim wrdDoc
Dim WordTable As Word.Table
Dim c As Integer
Set tbl = ThisWorkbook.Worksheets(Sheet2.Name).ListObjects("Table1").Range
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = False
Set wrdDoc = wrdApp.Documents.Open("C:\Users\Documents\Example")
With wrdDoc
tbl.Copy
wrdApp.Selection.Find.Text = "This is the section for the table to be pasted below it."
wrdApp.Selection.Find.Execute
wrdApp.Selection.MoveDown Unit:=wdLine, Count:=5, Extend:=wdMove
wrdApp.Selection.PasteExcelTable False, False, False
Dim objTable As Object
For Each objTable In ActiveDocument.Tables ' (This is where the error occurs)
objTable.AutoFitBehavior (wdAutoFitWindow)
objTable.AllowAutoFit = True
Next
wrdApp.Selection.GoTo wdGoToPage, wdGoToAbsolute, 1
wrdApp.Selection.GoTo What:=wdGoToTable, Which:=GoToNext
wrdApp.Selection.GoTo What:=wdGoToTable, Which:=GoToNext
wrdApp.Selection.GoTo What:=wdGoToTable, Which:=GoToNext
wrdApp.Selection.Tables(1).Select
With wrdApp.Selection.Borders(wdBorderTop)
.LineStyle = Options.DefaultBorderLineStyle
.LineWidth = Options.DefaultBorderLineWidth
.Color = Options.DefaultBorderColor
End With
With wrdApp.Selection.Borders(wdBorderLeft)
.LineStyle = Options.DefaultBorderLineStyle
.LineWidth = Options.DefaultBorderLineWidth
.Color = Options.DefaultBorderColor
End With
With wrdApp.Selection.Borders(wdBorderBottom)
.LineStyle = Options.DefaultBorderLineStyle
.LineWidth = Options.DefaultBorderLineWidth
.Color = Options.DefaultBorderColor
End With
With wrdApp.Selection.Borders(wdBorderRight)
.LineStyle = Options.DefaultBorderLineStyle
.LineWidth = Options.DefaultBorderLineWidth
.Color = Options.DefaultBorderColor
End With
With wrdApp.Selection.Borders(wdBorderHorizontal)
.LineStyle = Options.DefaultBorderLineStyle
.LineWidth = Options.DefaultBorderLineWidth
.Color = Options.DefaultBorderColor
End With
With wrdApp.Selection.Borders(wdBorderVertical)
.LineStyle = Options.DefaultBorderLineStyle
.LineWidth = Options.DefaultBorderLineWidth
.Color = Options.DefaultBorderColor
End With
wrdApp.Selection.Tables(1).Columns(3).Select
wrdApp.Selection.ParagraphFormat.Alignment = wdAlignParagraphRight
wrdApp.Selection.Tables(1).Columns(4).Select
wrdApp.Selection.ParagraphFormat.Alignment = wdAlignParagraphRight
Related
I have a problem. I am trying to get records from the data base to Excel and afterwards format the Excel file. If I implement the whole function then it will run fine on one occasion. But if I run it again it sometimes gives the runtime 91 error. I was going through the debugging and if I only have the first ApXl in the function the code will work fine with no issues. However, if I add more of the code to reformat the Excel sheet then it will eventually give me the run time 91 even though the variables are already declared. Below is part of my code with some of the formatting.
Public Function ExportToExcelEM(Numbcases, strObjectType As String, strObjectName As String, Optional strSheetName As String, Optional strFileName As String)
Dim rst As DAO.Recordset
Dim ApXL As Object
Dim xlWBk As Object
Dim xlWSh As Object
Dim intCount As Integer
Const xlToRight As Long = -4161
Const xlCenter As Long = -4108
Const xlBottom As Long = -4107
Const xlContinuous As Long = 1
Dim OBJ As Object
On Error GoTo ExportToExcel_Err
DoCmd.Hourglass True
Select Case strObjectType
Case "Table", "Query"
Set rst = CurrentDb.OpenRecordset(strObjectName, dbOpenDynaset, dbSeeChanges)
Case "Form"
Set rst = Forms(strObjectName).RecordsetClone
Case "Report"
Set rst = CurrentDb.OpenRecordset(Reports(strObjectName).RecordSource, dbOpenDynaset, dbSeeChanges)
End Select
If rst.RecordCount = 0 Then
MsgBox "No records to be exported.", vbInformation, GetDBTitle
DoCmd.Hourglass False
Else
On Error Resume Next
Set ApXL = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
Set ApXL = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo ExportToExcel_Err
Set xlWBk = ApXL.Workbooks.Add
ApXL.Visible = False
Set xlWSh = xlWBk.Worksheets("Sheet1")
If Len(strSheetName) > 0 Then
xlWSh.Name = Left(strSheetName, 31)
End If
xlWSh.Range("A1").Select
Do Until intCount = rst.Fields.Count
ApXL.ActiveCell = rst.Fields(intCount).Name
ApXL.ActiveCell.Offset(0, 1).Select
intCount = intCount + 1
Loop
rst.MoveFirst
xlWSh.Range("A2").CopyFromRecordset rst
** ** ** With ApXL
.Range("A1").Select
.Range(.Selection, .Selection.End(xlToRight)).Select
.Selection.Interior.Pattern = xlSolid
.Selection.Interior.PatternColorIndex = xlAutomatic
.Selection.Interior.TintAndShade = -0.25
.Selection.Interior.PatternTintAndShade = 0
.Selection.Borders.LineStyle = xlNone
.Selection.AutoFilter
.Cells.EntireColumn.AutoFit
.Cells.EntireRow.AutoFit
.Range("B2").Select
.ActiveWindow.FreezePanes = True
.ActiveSheet.Cells.Select
.ActiveSheet.Cells.WrapText = False
.ActiveSheet.Cells.EntireColumn.AutoFit
.Visible = False
End With********
With ApXL
xlWSh.Rows(1).Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
End With
xlWBk.SaveAs FileName:=strFileName, FileFormat:=51
xlWBk.Close
Set xlWBk = Nothing
Set xlWSh = Nothing
Set ApXL = Nothing
' end of doing anything with excel
End If
rst.Close
Set rst = Nothing
DoCmd.Hourglass False
ExportToExcel_Exit:
DoCmd.Hourglass False
Exit Function
ExportToExcel_Err:
DoCmd.SetWarnings True
Set xlWBk = Nothing
Set xlWSh = Nothing
Set ApXL = Nothing
rst.Close
MsgBox Err.Description, vbExclamation, Err.Number
DoCmd.Hourglass False
Resume ExportToExcel_Exit
End Function
debugging: works once after adding more formatting in my code but then gives me a runtime 91 error. I added more code chunks to the code till it was the complete excel function I desired. Throughout the process it would give me the finish piece I wanted but afterwards gives me a runtime error 91.
After running procedure, check if instance of Excel is still showing in Task Manager. This can be result of using Active______ referencing. Use explicit reference instead.
When I compile your procedure, I get "Method or data member not found." error on each line in the xlWSh.Rows(1).Select block. Use With .Rows(1) instead.
Could probably perform this process without actually selecting anything. Use explicit Cells or Range reference: With .Range("A1:E1") - construct reference with variables.
Modified your code to apply and it works:
intCount = rst.Fields.Count
Set xlWSh = xlWBk.worksheets("Sheet1")
With xlWSh
If strSheetName <> "" Then .Name = Left(strSheetName, 31)
For x = 1 To intCount
.Cells(1, x).Value = rst(x - 1).Name
Next
.Range("A2").CopyFromRecordset rst
With .Range(.Cells(1, 1), .Cells(1, intCount))
.Interior.Pattern = xlSolid
.Interior.PatternColorIndex = xlAutomatic
.Interior.TintAndShade = -0.25
.Interior.PatternTintAndShade = 0
.Borders.LineStyle = xlNone
.AutoFilter
.EntireColumn.AutoFit
End With
With .Rows(1)
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.shrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
.Rows.AutoFit
End With
ApXL.Windows(1).SplitColumn = 1
ApXL.Windows(1).SplitRow = 1
ApXL.Windows(1).FreezePanes = True
I'm trying to make a macro where users can select a table within a document and switch the orientation of the specific page it's on to landscape. I've tried both recording doing the action and writing the macro myself but it never seems to work properly. This is as close as I've gotten but it makes the page the table is on and everything before it landscape.
Sub TableLandscape()
'
' TableLandscape Macro
'
'
'Selection.Collapse Direction:=wdCollapseEnd
'Selection.InsertBreak Type:=wdSectionBreakContinuous
'ActiveDocument.Range(Start:=Selection.Start, End:=Selection.Start).Collapse Direction:=wdCollapseStart
'Selection.InsertBreak _
Type:=wdSectionBreakNextPage
Selection.Start = Selection.Start + 1
ActiveDocument.Range(Start:=Selection.End, End:=Selection.End).InsertBreak _
Type:=wdSectionBreakNextPage
With Selection.PageSetup
.LineNumbering.Active = False
.Orientation = wdOrientLandscape
.TopMargin = InchesToPoints(1)
.BottomMargin = InchesToPoints(1)
.LeftMargin = InchesToPoints(1)
.RightMargin = InchesToPoints(1)
.Gutter = InchesToPoints(0)
.HeaderDistance = InchesToPoints(0.6)
.FooterDistance = InchesToPoints(0.5)
.PageWidth = InchesToPoints(11)
.PageHeight = InchesToPoints(8.5)
.FirstPageTray = wdPrinterDefaultBin
.OtherPagesTray = wdPrinterDefaultBin
.SectionStart = wdSectionContinuous
.OddAndEvenPagesHeaderFooter = False
.DifferentFirstPageHeaderFooter = False
.VerticalAlignment = wdAlignVerticalTop
.SuppressEndnotes = False
.MirrorMargins = False
.TwoPagesOnOne = False
.BookFoldPrinting = False
.BookFoldRevPrinting = False
.BookFoldPrintingSheets = 1
.GutterPos = wdGutterPosLeft
End With
'ActiveDocument.Range(Start:=Selection.End, End:=Selection.End).InsertBreak _
'Type:=wdSectionBreakNextPage
End Sub
Here's how to do that:
Sub RotatePage()
Dim TableRange As Range, TableStart As Range, TableEnd As Range
Set TableRange = Selection.Tables(1).Range
Set TableStart = TableRange.Duplicate
With TableStart
.SetRange Start:=TableStart.Start - 1, End:=TableStart.End
.Collapse Direction:=wdCollapseStart
.InsertBreak Type:=wdSectionBreakNextPage
End With
Set TableEnd = TableRange.Duplicate
With TableEnd
.SetRange Start:=TableEnd.Start, End:=TableEnd.End + 1
.Collapse Direction:=wdCollapseEnd
.InsertBreak Type:=wdSectionBreakNextPage
End With
TableRange.PageSetup.Orientation = wdOrientLandscape
End Sub
I have an excel form that will open up ms word and go to the sixth table and adjust the cell margins. I want the left and right cell margins to be 0.08 for the entire table.
It works perfectly the first time the form is run, but the second time and after it won't do it. Here is my code. Can anyone tell me why this would happen?
Public Sub Table()
Dim wrdApp
Dim wrdDoc
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = False
Set wrdDoc = wrdApp.Documents.Open("\\FileLocation")
With wrdDoc
'Goes to 6th table and selects it
wrdApp.Selection.Goto wdGoToPage, wdGoToAbsolute, 1
wrdApp.Selection.Goto What:=wdGoToTable, Which:=GoToNext
wrdApp.Selection.Goto What:=wdGoToTable, Which:=GoToNext
wrdApp.Selection.Goto What:=wdGoToTable, Which:=GoToNext
wrdApp.Selection.Goto What:=wdGoToTable, Which:=GoToNext
wrdApp.Selection.Goto What:=wdGoToTable, Which:=GoToNext
wrdApp.Selection.Goto What:=wdGoToTable, Which:=GoToNext
wrdApp.Selection.Tables(1).Select
With wrdApp.Selection.Tables(1)
.TopPadding = InchesToPoints(0)
.BottomPadding = InchesToPoints(0)
.LeftPadding = InchesToPoints(0.08)
.RightPadding = InchesToPoints(0.08)
.Spacing = 0
.AllowPageBreaks = True
.AllowAutoFit = True
End With
End Sub
Why are you using wrdApp.Selection.Goto What:=wdGoToTable, Which:=GoToNext? Why not Set wrdTbl = wrdDoc.Tables(6) and work with that? All that code may be referring to another table?
Try something like this:
Private Sub Sample()
Dim wrdApp As Object, wrdDoc As Object, wrdTbl As Object
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = False
Set wrdDoc = wrdApp.Documents.Open("\\FileLocation")
Set wrdTbl = wrdDoc.Tables(6)
With wrdTbl
.TopPadding = wrdApp.InchesToPoints(0)
.BottomPadding = wrdApp.InchesToPoints(0)
.LeftPadding = wrdApp.InchesToPoints(0.08)
.RightPadding = wrdApp.InchesToPoints(0.08)
.Spacing = 0
.AllowPageBreaks = True
.AllowAutoFit = True
End With
End Sub
I want to create a Word macro that can do the following task at a single click.
Please help me.
I have a large document that's a trouble for me.
The task includes a table formatting such as
table width 11 cm,
left aligned,
font TNR 10,
border black,
indent from left is zero.
I got the macro code....
Thanks..
Sub Macro1()
With Selection.tables(1)
.Rows.HeightRule = wdRowHeightAuto
.PreferredWidthType = wdPreferredWidthPoints
.PreferredWidth = CentimetersToPoints(11)
End With
With Selection.Borders(wdBorderTop)
.LineStyle = Options.DefaultBorderLineStyle
.LineWidth = Options.DefaultBorderLineWidth
.Color = Options.DefaultBorderColor
End With
With Selection.Borders(wdBorderLeft)
.LineStyle = Options.DefaultBorderLineStyle
.LineWidth = Options.DefaultBorderLineWidth
.Color = Options.DefaultBorderColor
End With
With Selection.Borders(wdBorderBottom)
.LineStyle = Options.DefaultBorderLineStyle
.LineWidth = Options.DefaultBorderLineWidth
.Color = Options.DefaultBorderColor
End With
With Selection.Borders(wdBorderRight)
.LineStyle = Options.DefaultBorderLineStyle
.LineWidth = Options.DefaultBorderLineWidth
.Color = Options.DefaultBorderColor
End With
With Selection.Borders(wdBorderVertical)
.LineStyle = Options.DefaultBorderLineStyle
.LineWidth = Options.DefaultBorderLineWidth
.Color = Options.DefaultBorderColor
End With
With Selection.Borders(wdBorderHorizontal)
.LineStyle = Options.DefaultBorderLineStyle
.LineWidth = Options.DefaultBorderLineWidth
.Color = Options.DefaultBorderColor
End With
Selection.ParagraphFormat.Alignment = wdAlignParagraphLeft
With Selection.ParagraphFormat
.LeftIndent = CentimetersToPoints(0)
.RightIndent = CentimetersToPoints(0)
.SpaceBefore = 0
.SpaceBeforeAuto = False
.SpaceAfter = 0
.SpaceAfterAuto = False
.LineSpacingRule = wdLineSpaceSingle
.Alignment = wdAlignParagraphLeft
.WidowControl = True
.KeepWithNext = False
.KeepTogether = False
.PageBreakBefore = False
.NoLineNumber = False
.Hyphenation = True
.FirstLineIndent = CentimetersToPoints(0)
.OutlineLevel = wdOutlineLevelBodyText
.CharacterUnitLeftIndent = 0
.CharacterUnitRightIndent = 0
.CharacterUnitFirstLineIndent = 0
.LineUnitBefore = 0
.LineUnitAfter = 0
.MirrorIndents = False
.TextboxTightWrap = wdTightNone
.CollapsedByDefault = False
End With
With Selection.ParagraphFormat
.LeftIndent = CentimetersToPoints(0)
.RightIndent = CentimetersToPoints(0)
.SpaceBefore = 0
.SpaceBeforeAuto = False
.SpaceAfter = 0
.SpaceAfterAuto = False
.LineSpacingRule = wdLineSpaceSingle
.Alignment = wdAlignParagraphLeft
.WidowControl = True
.KeepWithNext = False
.KeepTogether = False
.PageBreakBefore = False
.NoLineNumber = False
.Hyphenation = True
.FirstLineIndent = CentimetersToPoints(0)
.OutlineLevel = wdOutlineLevelBodyText
.CharacterUnitLeftIndent = 0
.CharacterUnitRightIndent = 0
.CharacterUnitFirstLineIndent = 0
.LineUnitBefore = 0
.LineUnitAfter = 0
.MirrorIndents = False
.TextboxTightWrap = wdTightNone
.CollapsedByDefault = False
End With
With Selection.tables(1).Rows
.Alignment = wdAlignRowLeft
.AllowBreakAcrossPages = True
.SetLeftIndent LeftIndent:=CentimetersToPoints(0), RulerStyle:= _
wdAdjustNone
End With
End Sub
Sub GetPictures()
Dim sPic As String
Dim sPath As String
Dim sCount As Long
sPath = "G:\Images\Alphabet_Lower_Case\"
sPic = Dir(sPath & "*.jpg")
Do While sPic <> ""
Selection.InlineShapes.AddPicture _
FileName:=sPath & sPic, _
LinkToFile:=False, SaveWithDocument:=True
With Selection
With .Borders(wdBorderLeft)
.LineStyle = wdLineStyleSingle
.LineWidth = wdLineWidth300pt
.Color = wdColorAutomatic
End With
With .Borders(wdBorderRight)
.LineStyle = wdLineStyleSingle
.LineWidth = wdLineWidth300pt
.Color = wdColorAutomatic
End With
With .Borders(wdBorderTop)
.LineStyle = wdLineStyleSingle
.LineWidth = wdLineWidth300pt
.Color = wdColorAutomatic
End With
With .Borders(wdBorderBottom)
.LineStyle = wdLineStyleSingle
.LineWidth = wdLineWidth300pt
.Color = wdColorAutomatic
End With
.Borders.Shadow = False
End With
Selection.Paragraphs.Format.Alignment = wdAlignParagraphCenter
sPic = Dir
With Selection
.Collapse Direction:=wdCollapseEnd
.TypeParagraph
End With
Loop
With ThisDocument.PageSetup.TextColumns
.SetCount NumColumns:=2
End With
Selection.MoveRight Unit:=wdCharacter, Count:=1, Extend:=wdExtend
Selection.Cut
End Sub
'Any idea on how to lower the image on the right hand side to the same level as the one of the left (previous)? E.g. b is sitting higher than it should be and is occluding the border.
All images have the same 600x600 dimension.
See the following output for clarification.
a&b
Here's a screen capture and the grid behind 'b' shows the shift.
preview