Im not good in Visual Basic but I have task to make macros from 32 bit windows excel available on 64 bit window :)
The task is to make EMF from Excel page - I`ve already changed "function" to "PtrSafe function" and "olepro32.dll" to "oleaut32.dll" but code is running with error - RunTime error "380" Invalid property value
Sub UpdateRtLogsandEMF()
Set This = ThisWorkbook
Dim aaa1 As Single
Dim aaa2 As Single
Application.ScreenUpdating = False
This.Worksheets("TempSQL").Visible = xlSheetVisible
This.Worksheets("TempLog").Visible = xlSheetVisible
This.Worksheets("TempLog").Select
Set cn = New ADODB.Connection
sCon = This.Worksheets("TempSQL").Cells(1, 1)
cn.Open sCon
DrillDepthIndex = This.Worksheets("TempLog").Cells(1, 157)
DrillDepthIndex = "'" & DrillDepthIndex & "'"
WellPathIndex = This.Worksheets("TempLog").Cells(1, 154)
WellPathIndex = "'" & WellPathIndex & "'"
Set rs = New ADODB.Recordset
sql_query = "SELECT Depth FROM GENDATAINDEX WHERE GenDataSetId = " & DrillDepthIndex & "ORDER BY Time DESC"
rs.Open sql_query, cn
On Error Resume Next
sss = rs.Fields(0)
If sss = "" Then
This.Worksheets("Logs RT").Cells(14, 19) = ""
Else
This.Worksheets("Logs RT").Cells(14, 19) = Round(rs.Fields(0), 2)
End If
'This.Worksheets("Logs RT").Cells(14, 19) = Round(rs.Fields(0), 2)
Date1 = Format(Now, "yyyy.mm.dd")
Day1 = Right(Date1, 2)
Year1 = Left(Date1, 4)
Month1 = Mid(Date1, 6, 2)
If This.Worksheets("TempLog").Cells(1, 210) = "RUS" Then
dfd = 43
Else
dfd = 42
End If
This.Worksheets("Logs RT").Cells(11, 15) = Day1 & " " & This.Worksheets("Logs RT").Cells(Month1, dfd) & " " & Year1
This.Worksheets("Logs RT").Cells(12, 15) = Format(Now, "HH:mm")
This.Worksheets("Logs RT").Select
Set rs = New ADODB.Recordset
sql_query = "SELECT SRSP_S_VDEPTH FROM SURVEY_STATION WHERE PATH_IDENTIFIER = " & WellPathIndex & " ORDER BY SRSP_TIME DESC"
rs.Open sql_query, cn
On Error Resume Next
sss = rs.Fields(0)
If sss = "" Then
This.Worksheets("Logs RT").Cells(14, 62) = ""
Else
This.Worksheets("Logs RT").Cells(14, 62) = Round(rs.Fields(0), 2)
End If
If This.Worksheets("TempLog").Cells(9, 151) = True Then
aaa1 = apiGetSystemMetrics(0&)
aaa2 = apiGetSystemMetrics(1&)
ChangeResolution 1280, 960
End If
' With Application.ErrorCheckingOptions
' .TextDate = False
' .NumberAsText = False
' .InconsistentFormula = False
' .UnlockedFormulaCells = False
' .EmptyCellReferences = False
' End With
' If ActiveWindow.DisplayGridlines Then
' bGridOn = True
' ActiveWindow.DisplayGridlines = False
' End If
Dim vFile As Variant, sFilter As String, lPicType As Long, oPic As IPictureDisp
sFilter = "Windows Metafile (*.emf),*.emf"
vFile = This.Worksheets("TempLog").Cells(1, 152) & "RT_header_MD.emf"
lPicType = xlPicture
This.Worksheets("Logs RT").Range(Cells(2, 2), Cells(67, 32)).Select
With Selection
.CopyPicture Appearance:=xlScreen, Format:=xlPicture
End With
Set oPic = PastePicture(lPicType)
SavePicture oPic, vFile
sFilter = "Windows Metafile (*.emf),*.emf"
vFile = This.Worksheets("TempLog").Cells(1, 152) & "RT_header_TVD.emf"
lPicType = xlPicture
This.Worksheets("Logs RT").Range(Cells(2, 45), Cells(67, 75)).Select
With Selection
.CopyPicture Appearance:=xlScreen, Format:=xlPicture
End With
Set oPic = PastePicture(lPicType)
SavePicture oPic, vFile
' If bGridOn Then ActiveWindow.DisplayGridlines = True
' With Application.ErrorCheckingOptions
' .TextDate = True
' .NumberAsText = True
' .InconsistentFormula = True
' .UnlockedFormulaCells = True
' .EmptyCellReferences = True
' End With
If This.Worksheets("TempLog").Cells(9, 151) = True Then
ChangeResolution aaa1, aaa2
End If
This.Worksheets("Logs RT").Select
This.Worksheets("TempSQL").Visible = xlSheetHidden
This.Worksheets("TempLog").Visible = xlSheetHidden
Application.ScreenUpdating = True
End Sub
Sub MakeRtLogsEMF()
Application.ScreenUpdating = False
Set This = ThisWorkbook
Dim aaa1 As Single
Dim aaa2 As Single
If This.Worksheets("TempLog").Cells(9, 151) = True Then
aaa1 = apiGetSystemMetrics(0&)
aaa2 = apiGetSystemMetrics(1&)
ChangeResolution 1280, 960
End If
Set This = ThisWorkbook
' With Application.ErrorCheckingOptions
' .TextDate = False
' .NumberAsText = False
' .InconsistentFormula = False
' .UnlockedFormulaCells = False
' .EmptyCellReferences = False
' End With
' If ActiveWindow.DisplayGridlines Then
' bGridOn = True
' ActiveWindow.DisplayGridlines = False
' End If
Dim vFile As Variant, sFilter As String, lPicType As Long, oPic As IPictureDisp
sFilter = "Windows Metafile (*.emf),*.emf"
vFile = This.Worksheets("TempLog").Cells(1, 152) & "RT_header_MD.emf"
'Get the type of bitmap
lPicType = xlPicture
'Copy a picture to the clipboard
This.Worksheets("Logs RT").Range(Cells(2, 2), Cells(67, 32)).Select
With Selection
.CopyPicture Appearance:=xlScreen, Format:=xlPicture
End With
'Retrieve the picture from the clipboard...
Set oPic = PastePicture(lPicType)
'... and save it to the file
SavePicture oPic, vFile
sFilter = "Windows Metafile (*.emf),*.emf"
vFile = This.Worksheets("TempLog").Cells(1, 152) & "RT_header_TVD.emf"
'Get the type of bitmap
lPicType = xlPicture
'Copy a picture to the clipboard
This.Worksheets("Logs RT").Range(Cells(2, 45), Cells(67, 75)).Select
With Selection
.CopyPicture Appearance:=xlScreen, Format:=xlPicture
End With
'Retrieve the picture from the clipboard...
Set oPic = PastePicture(lPicType)
'... and save it to the file
SavePicture oPic, vFile
' If bGridOn Then ActiveWindow.DisplayGridlines = True
'
' With Application.ErrorCheckingOptions
' .TextDate = True
' .NumberAsText = True
' .InconsistentFormula = True
' .UnlockedFormulaCells = True
' .EmptyCellReferences = True
' End With
If This.Worksheets("TempLog").Cells(9, 151) = True Then
ChangeResolution aaa1, aaa2
End If
Application.ScreenUpdating = True
End Sub
Sub MakeTailEMF()
Application.ScreenUpdating = False
Set This = ThisWorkbook
Dim aaa1 As Single
Dim aaa2 As Single
If This.Worksheets("TempLog").Cells(9, 151) = True Then
aaa1 = apiGetSystemMetrics(0&)
aaa2 = apiGetSystemMetrics(1&)
ChangeResolution 1280, 960
End If
Set This = ThisWorkbook
' With Application.ErrorCheckingOptions
' .TextDate = False
' .NumberAsText = False
' .InconsistentFormula = False
' .UnlockedFormulaCells = False
' .EmptyCellReferences = False
' End With
' If ActiveWindow.DisplayGridlines Then
' bGridOn = True
' ActiveWindow.DisplayGridlines = False
' End If
Dim vFile As Variant, sFilter As String, lPicType As Long, oPic As IPictureDisp
sFilter = "Windows Metafile (*.emf),*.emf"
vFile = This.Worksheets("TempLog").Cells(1, 152) & "RT_tail.emf"
'Get the type of bitmap
lPicType = xlPicture
'Copy a picture to the clipboard
This.Worksheets("Logs RT").Range(Cells(70, 2), Cells(78, 32)).Select
With Selection
.CopyPicture Appearance:=xlScreen, Format:=xlPicture
End With
'Retrieve the picture from the clipboard...
Set oPic = PastePicture(lPicType)
'... and save it to the file
SavePicture oPic, vFile
' If bGridOn Then ActiveWindow.DisplayGridlines = True
'
' With Application.ErrorCheckingOptions
' .TextDate = True
' .NumberAsText = True
' .InconsistentFormula = True
' .UnlockedFormulaCells = True
' .EmptyCellReferences = True
' End With
If This.Worksheets("TempLog").Cells(9, 151) = True Then
ChangeResolution aaa1, aaa2
End If
Application.ScreenUpdating = True
End Sub
Sub UpdateRtLogsandEMF_woDepth()
Set This = ThisWorkbook
Dim aaa1 As Single
Dim aaa2 As Single
Application.ScreenUpdating = False
This.Worksheets("TempSQL").Visible = xlSheetVisible
This.Worksheets("TempLog").Visible = xlSheetVisible
This.Worksheets("TempLog").Select
Set cn = New ADODB.Connection
sCon = This.Worksheets("TempSQL").Cells(1, 1)
cn.Open sCon
'DrillDepthIndex = This.Worksheets("TempLog").Cells(1, 157)
'DrillDepthIndex = "'" & DrillDepthIndex & "'"
'WellPathIndex = This.Worksheets("TempLog").Cells(1, 154)
'WellPathIndex = "'" & WellPathIndex & "'"
'Set rs = New ADODB.Recordset
'sql_query = "SELECT Depth FROM GENDATAINDEX WHERE GenDataSetId = " & DrillDepthIndex & "ORDER BY Time DESC"
'rs.Open sql_query, cn
'On Error Resume Next
'sss = rs.Fields(0)
'If sss = "" Then
'This.Worksheets("Logs RT").Cells(14, 19) = ""
'Else
'This.Worksheets("Logs RT").Cells(14, 19) = Round(rs.Fields(0), 2)
'End If
'This.Worksheets("Logs RT").Cells(14, 19) = Round(rs.Fields(0), 2)
Date1 = Format(Now, "yyyy.mm.dd")
Day1 = Right(Date1, 2)
Year1 = Left(Date1, 4)
Month1 = Mid(Date1, 6, 2)
This.Worksheets("Logs RT").Cells(11, 15) = Day1 & " " & This.Worksheets("Logs RT").Cells(Month1, 43) & " " & Year1
This.Worksheets("Logs RT").Cells(12, 15) = Format(Now, "HH:mm")
This.Worksheets("Logs RT").Select
'Set rs = New ADODB.Recordset
'sql_query = "SELECT SRSP_S_VDEPTH FROM SURVEY_STATION WHERE PATH_IDENTIFIER = " & WellPathIndex & " ORDER BY SRSP_TIME DESC"
'rs.Open sql_query, cn
'On Error Resume Next
'sss = rs.Fields(0)
'If sss = "" Then
'This.Worksheets("Logs RT").Cells(14, 62) = ""
'Else
'This.Worksheets("Logs RT").Cells(14, 62) = Round(rs.Fields(0), 2)
'End If
If This.Worksheets("TempLog").Cells(9, 151) = True Then
aaa1 = apiGetSystemMetrics(0&)
aaa2 = apiGetSystemMetrics(1&)
ChangeResolution 1280, 960
End If
' With Application.ErrorCheckingOptions
' .TextDate = False
' .NumberAsText = False
' .InconsistentFormula = False
' .UnlockedFormulaCells = False
' .EmptyCellReferences = False
' End With
' If ActiveWindow.DisplayGridlines Then
' bGridOn = True
' ActiveWindow.DisplayGridlines = False
' End If
Dim vFile As Variant, sFilter As String, lPicType As Long, oPic As IPictureDisp
sFilter = "Windows Metafile (*.emf),*.emf"
vFile = This.Worksheets("TempLog").Cells(1, 152) & "RT_header_MD.emf"
lPicType = xlPicture
This.Worksheets("Logs RT").Range(Cells(2, 2), Cells(67, 32)).Select
With Selection
.CopyPicture Appearance:=xlScreen, Format:=xlPicture
End With
Set oPic = PastePicture(lPicType)
SavePicture oPic, vFile
sFilter = "Windows Metafile (*.emf),*.emf"
vFile = This.Worksheets("TempLog").Cells(1, 152) & "RT_header_TVD.emf"
lPicType = xlPicture
This.Worksheets("Logs RT").Range(Cells(2, 45), Cells(67, 75)).Select
With Selection
.CopyPicture Appearance:=xlScreen, Format:=xlPicture
End With
Set oPic = PastePicture(lPicType)
SavePicture oPic, vFile
' If bGridOn Then ActiveWindow.DisplayGridlines = True
' With Application.ErrorCheckingOptions
' .TextDate = True
' .NumberAsText = True
' .InconsistentFormula = True
' .UnlockedFormulaCells = True
' .EmptyCellReferences = True
' End With
If This.Worksheets("TempLog").Cells(9, 151) = True Then
ChangeResolution aaa1, aaa2
End If
This.Worksheets("Logs RT").Select
This.Worksheets("TempSQL").Visible = xlSheetHidden
This.Worksheets("TempLog").Visible = xlSheetHidden
Application.ScreenUpdating = True
End Sub
Debugger stops at "SavePicture oPic, vFile"
Related
I have used the following code before and worked as expected for a handful times. 4 hours later it did not work. I added the MsgBox "File: " and confirm the filename path is error free.
Option Explicit
Sub ExportAsPDF()
Dim Folder_Path As String
Dim NameOfWorkbook
NameOfWorkbook = Left(ActiveWorkbook.Name, (InStrRev(ActiveWorkbook.Name, ".", -1, vbTextCompare) - 1))
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select Folder path"
If .Show = -1 Then Folder_Path = .SelectedItems(1)
End With
If Folder_Path = "" Then Exit Sub
Dim sh As Worksheet
Dim fn As String
For Each sh In ActiveWorkbook.Worksheets
fn = Folder_Path & Application.PathSeparator & NameOfWorkbook & "_" & sh.Name & ".pdf"
MsgBox "File: " & fn
sh.PageSetup.PaperSize = xlPaperA4
sh.PageSetup.LeftMargin = Application.InchesToPoints(0.5)
sh.PageSetup.RightMargin = Application.InchesToPoints(0.5)
sh.PageSetup.TopMargin = Application.InchesToPoints(0.5)
sh.PageSetup.BottomMargin = Application.InchesToPoints(0.5)
sh.PageSetup.HeaderMargin = Application.InchesToPoints(0.5)
sh.PageSetup.FooterMargin = Application.InchesToPoints(0.5)
sh.PageSetup.Orientation = xlPortrait
sh.PageSetup.CenterHorizontally = True
sh.PageSetup.CenterVertically = False
sh.PageSetup.FitToPagesTall = 1
sh.PageSetup.FitToPagesWide = 1
sh.PageSetup.Zoom = False
sh.ExportAsFixedFormat Type:=xlTypePDF, Filename:=fn, Quality:=xlQualityStandard, OpenAfterPublish:=True
Next
MsgBox "Done"
End Sub
Is there anything I missed?
Microsoft® Excel® for Microsoft 365 MSO (Version 2211 Build 16.0.15831.20220) 64-bit
If the ActiveWorkbook is new and was never stored, the workbook name is a generic name without any extension, eg Book1. In that case, InStrRev(ActiveWorkbook.Name, ".", -1, vbTextCompare) will return 0. Because you are nesting two commands, this 0 will be passed as parameter to the Left function, and Left(Name, 0) throws that runtime error 5.
Workaround: Write the result of InstrRev into an intermediate variable and check it. My advice is to avoid nested commands because it is much harder to check what exactly fails if there is an error because 0 is an invalid parameter.
Dim p As Long
p = InStrRev(ActiveWorkbook.Name, ".")
If p = 0 Then
NameOfWorkbook = ActiveWorkbook.Name
Else
NameOfWorkbook = Left(ActiveWorkbook.Name, p - 1)
End If
An alternative way to get the filename without extension is to use the FileSystemObject-method GetBaseName (will not work on a Mac)
nameOfWorkbook = CreateObject("Scripting.fileSystemObject").GetBasename(ActiveWorkbook.FullName)
Export Worksheets to Single PDFs
I could produce the error only when a worksheet was not visible (hidden or very hidden). The following deals with that and a few more issues.
Sub ExportAsPDF()
Const PROC_TITLE As String = "Export As PDF"
Const EXPORT_ONLY_VISIBLE_WORKSHEETS As Boolean = False
If ActiveWorkbook Is Nothing Then
MsgBox "No visible workbooks open.", vbExclamation, PROC_TITLE
Exit Sub
End If
Dim swb As Workbook: Set swb = ActiveWorkbook
If Len(swb.Path) = 0 Then
MsgBox "The workbook was not saved yet." & vbLf & vbLf _
& "Save it and try again.", vbExclamation, PROC_TITLE
Exit Sub
End If
Dim dFolderPath As String
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select Folder path"
If .Show Then dFolderPath = .SelectedItems(1)
End With
If Len(dFolderPath) = 0 Then
MsgBox "No folder selected.", vbExclamation, PROC_TITLE
Exit Sub
End If
Dim swbBaseName As String: swbBaseName = swb.Name
swbBaseName = Left(swbBaseName, InStrRev(swbBaseName, ".") - 1)
Dim dFilePathLeft As String
dFilePathLeft = dFolderPath & Application.PathSeparator & swbBaseName & "_"
Dim sVisibility As XlSheetVisibility: sVisibility = xlSheetVisible
Dim sws As Worksheet
Dim dCount As Long
Dim dFilePath As String
Dim DoExport As Boolean
For Each sws In swb.Worksheets
With sws
If EXPORT_ONLY_VISIBLE_WORKSHEETS Then ' only visible
If .Visible = xlSheetVisible Then DoExport = True
Else ' all
If Not .Visible = xlSheetVisible Then
sVisibility = .Visible ' store
.Visible = xlSheetVisible ' make visible
End If
DoExport = True
End If
If DoExport Then
With .PageSetup
.PaperSize = xlPaperA4
.LeftMargin = Application.InchesToPoints(0.5)
.RightMargin = Application.InchesToPoints(0.5)
.TopMargin = Application.InchesToPoints(0.5)
.BottomMargin = Application.InchesToPoints(0.5)
.HeaderMargin = Application.InchesToPoints(0.5)
.FooterMargin = Application.InchesToPoints(0.5)
.Orientation = xlPortrait
.CenterHorizontally = True
.CenterVertically = False
.FitToPagesTall = 1
.FitToPagesWide = 1
.Zoom = False
End With
dFilePath = dFilePathLeft & .Name & ".pdf"
.ExportAsFixedFormat Type:=xlTypePDF, Filename:=dFilePath, _
Quality:=xlQualityStandard, OpenAfterPublish:=True
dCount = dCount + 1
DoExport = False ' reset for the next iteration
End If
If Not EXPORT_ONLY_VISIBLE_WORKSHEETS Then ' all
If Not sVisibility = xlSheetVisible Then
.Visible = sVisibility ' revert
sVisibility = xlSheetVisible ' reset
End If
End If
End With
Next sws
MsgBox dCount & " worksheet" & IIf(dCount = 1, "", "s") & " exported.", _
vbInformation, PROC_TITLE
End Sub
When I try to generate a word document, it gets stopped at the 80% progress bar and it shows the following error.
When I try to debug it, I see this
I'm getting error in now For i = 1 To .InlineShapes.Count
My code
Sub FillABookmark(strBM As String, strText As String)
Dim j As Long
With ActiveDocument
.Bookmarks(strBM).Range _
.InlineShapes _
.AddPicture FileName:=strText
j = ActiveDocument.InlineShapes.Count
.InlineShapes(j).Select
.Bookmarks.Add strBM, Range:=Selection.Range
End With
End Sub
Sub AddImage(strFile As String, addOrAfter As Boolean)
Dim oImage As Object
'Dim oDialog As Dialog
' Dim oRng As Object
' Set oDialog = Dialogs(wdDialogInsertPicture)
' With oDialog
' .Display
' If .Name <> "" Then
' strFile = .Name
' End If
'End With
'Selection.Move 6, -1 'moverse al principio del documento
'Selection.Find.Execute FindText:="[aud_sig_1]"
'If Selection.Find.Found = True Then
If (addOrAfter) Then
Set oImage = Selection.InlineShapes.AddPicture(strFile, False, True)
'With oRng
' .RelativeHorizontalPosition = _
' wdRelativeHorizontalPositionPage
' .RelativeVerticalPosition = _
' wdRelativeVerticalPositionPage
'.Left = CentimetersToPoints(0)
'.Top = CentimetersToPoints(4.5)
'End With
Else
Selection.TypeParagraph
Selection.TypeParagraph
Selection.TypeParagraph
Selection.TypeParagraph
Selection.TypeParagraph
Set oImage = Selection.InlineShapes.AddPicture(strFile, False, True)
End If
With oImage
.LockAspectRatio = msoFalse
.Height = CentimetersToPoints(1.5)
.Width = CentimetersToPoints(2.1)
Set oRng = .ConvertToShape
End With
Set oDialog = Nothing
Set oImage = Nothing
Set oRng = Nothing
End Sub
Sub PicWithCaption(xPath, Optional ByVal imgType As String = "All")
Dim xFileDialog As FileDialog
Dim xFile As Variant
Dim doc As Document
'******Test
'Set doc = Application.ActiveDocument
'xPath = "C:\phototest\"
'doc.Bookmarks.Exists ("photos")
'doc.Bookmarks("photos").Select 'select the bookmark
'*****End test
Dim x, w, c
Dim oTbl As Word.Table, i As Long, j As Long, k As Long, StrTxt As String
Set oTbl = Selection.Tables.Add(Selection.Range, 2, 3)
With oTbl
.AutoFitBehavior (wdAutoFitFixed)
.Columns.Width = CentimetersToPoints(9)
'Format the rows
Call FormatRows(oTbl, 1)
End With
If xPath <> "" Then
xFile = Dir(xPath & "\*.*")
i = 1
CaptionLabels.Add Name:="Picture"
Do While xFile <> ""
If (UCase(Right(xFile, 3)) = "PNG" Or _
UCase(Right(xFile, 3)) = "TIF" Or _
UCase(Right(xFile, 3)) = "JPG" Or _
UCase(Right(xFile, 3)) = "GIF" Or _
UCase(Right(xFile, 3)) = "BMP") And (imgType = "All" Or UCase(Left(xFile, 1) <> imgType)) Then
j = Int((i + 2) / 3) * 2 - 1
k = (i - 1) Mod 3 + 1
'Add extra rows as needed
If j > oTbl.Rows.Count Then
oTbl.Rows.Add
oTbl.Rows.Add
Call FormatRows(oTbl, j)
End If
'Insert the Picture
'Dim shape As InlineShape
' ActiveDocument.InlineShapes.AddPicture _
' FileName:=xPath & "\" & xFile, LinkToFile:=False, _
' SaveWithDocument:=True, Range:=oTbl.Rows(j).Cells(k).Range
Set shape = ActiveDocument.InlineShapes.AddPicture(xPath & "\" & xFile, False, True, oTbl.Rows(j).Cells(k).Range)
oTbl.Rows(j).Cells(k).Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
' With shape
' .LockAspectRatio = msoTrue
' If .Width > .Height Then
' .Height = InchesToPoints(1.75)
' Else
' .Width = InchesToPoints(1.75)
' End If
' End With
'shape.ScaleWidth = 50
'Get the Image name for the Caption
'StrTxt = Split(xPath & "\" & xFile, "\")(UBound(Split(.SelectedItems(i), "\")))
StrTxt = xFile
StrTxt = ": " & Split(StrTxt, ".")(0)
'Insert the Caption on the row below the picture
With oTbl.Rows(j + 1).Cells(k).Range
.InsertBefore vbCr
.Characters.First.InsertParagraph
.InsertBefore StrTxt
.ParagraphFormat.Alignment = wdAlignParagraphCenter
.Font.Bold = True
.Characters.First = vbNullString
.Characters.Last.Previous = vbNullString
End With
End If
i = i + 1
xFile = Dir()
Loop
End If
'End If
End Sub
Sub FormatRows(oTbl As Table, x As Long)
With oTbl
With .Rows(x)
.Height = CentimetersToPoints(6)
.HeightRule = wdRowHeightExactly
.Range.Style = "Normal"
.Alignment = wdAlignRowCenter
End With
With .Rows(x + 1)
.Height = CentimetersToPoints(1.2)
.HeightRule = wdRowHeightExactly
.Range.Style = "Caption"
.Alignment = wdAlignRowCenter
End With
End With
End Sub
Sub rezie()
Dim i As Long
With ThisDocument
For i = 1 To .InlineShapes.Count
Next i
End With
End Sub
Use the style enums to be on the safe side when on a non-english system:
.Range.Style = Word.wdStyleCaption (in case you are using early binding - what you are using)
In case of late binding: .Range.style = -35
this is my code
Sub teste3()
' Application.ScreenUpdating = False
Dim car As Variant Dim caminho As String
ReDim car(1 To 4)
Set b = ThisWorkbook.ActiveSheet
For i = 4 To 100000
If b.Cells(i, 9) = Empty Then Exit For
' Number of columns in the staging area
car(1) = b.Cells(i, 9)
car(2) = b.Cells(i, 10)
car(3) = b.Cells(i, 12)
car(4) = b.Cells(i, 14)
Range("B16").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = car(3)
Range("B17").Select
Range("B17").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = car(4)
Range("B18").Select
Dim oWs As Worksheet Dim oRng As Range Dim oChrtO As ChartObject Dim
lWidth As Long, lHeight As Long
Set oWs = ActiveSheet
Set oRng = oWs.Range("A1:F13")
oRng.CopyPicture xlScreen, xlPicture
lWidth = oRng.Width lHeight = oRng.Height
Set oChrtO = oWs.ChartObjects.Add(Left:=0, Top:=0, Width:=lWidth,
Height:=lHeight)
oChrtO.Activate With oChrtO.Chart
.Paste
'.sa Filename:=EstaPastaDeTrabalho.Path & car(1) & "_" & Replace(car(2), "/", "_") & "_Barr_" & car(3) * 100 & "_cup_" & car(4)
* 100 & ".jpg"
.Export Filename:=ThisWorkbook.Path & car(1) & "_" & Replace(car(2), "/", "_") & "_Barr_" & car(3) * 100 & "_cup_" & car(4)
* 100 & ".jpg"
'Set down 1 row from present location End With
oChrtO.Delete
Next i
'With Application ' ' .ScreenUpdating = True ' .DisplayAlerts = True ' .Calculation = xlCalculationAutomatic
End Sub
but the file is not saving in my directory, hi is saving a pasth before this, how can I do this code better?
I need him to save these files in the folder where the macro is saved, but I can't put the name of the folder because I want to change it from the folder and make it keep saving only in the name folder, without me changing the name
I created the macro below (my first time macro ever) to automatically generate PDFs in bulk, creating one per row populating a Word template with the corresponding fields. Now, I need to filter the data to generate PDFs only for the remaining visible rows, but cant figure out what lines of the code to modify to make this happen. I have read about the .SpecialCells(xlCellTypeVisible) but I have no idea where to use it nor if it is even the way to go. I would greatly appreciate some help. Thanks!
Sub PrintPrivacyPolicyDoc_EN()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim objWord As Word.Application, wdDoc As Word.Document
Dim datos(0 To 1, 0 To 9) As String
Set a = Sheets(ActiveSheet.Name)
nom = ActiveWorkbook.Name
pto = InStr(nom, ".")
nomarch = Left(nom, pto - 1)
wArch = ThisWorkbook.Path & "\" & a.Range("B3").Text & ".dotx"
uf = a.Range("A" & Rows.Count).End(xlUp).Row
Set objWord = CreateObject("Word.Application")
objWord.DisplayAlerts = wdAlertsNone
objWord.Visible = True
uf = a.Range("A" & Rows.Count).End(xlUp).Row
Set objWord = CreateObject("Word.Application")
objWord.DisplayAlerts = wdAlertsNone
objWord.Visible = True
For j = 5 To uf
Set wdDoc = objWord.Documents.Open(wArch)
nomfic = nomarch & "_" & a.Cells(j, "A") & "_" & a.Range("C3").Text
rutainf = ThisWorkbook.Path & "\" & "PrivacyPolicy PDFs" & "\" & nomfic & ".pdf"
'Variables to find and text to substitute"
datos(0, 0) = "[Company_Name]"
datos(1, 0) = a.Cells(j, "B")
datos(0, 1) = "[Vat_Number]"
datos(1, 1) = a.Cells(j, "C")
datos(0, 2) = "[URL_Stay]"
datos(1, 2) = a.Cells(j, "D")
datos(0, 3) = "[Update_Date]"
datos(1, 3) = a.Cells(j, "E")
For I = 0 To UBound(datos, 2)
textobuscar = datos(0, I)
objWord.Selection.Move 6, -1
objWord.Selection.Find.Execute FindText:=textobuscar
While objWord.Selection.Find.Found = True
objWord.Selection.Text = datos(1, I) 'texto a reemplazar
objWord.Selection.Move 6, -1
objWord.Selection.Find.Execute FindText:=textobuscar
Wend
Next I
'Search for the file and delete it before saving the newest verion
If Dir(rutaInf) <> "" Then
Kill rutaInf
End If
'Save file with the designated name
wdDoc.SaveAs Filename:=rutaInf, FileFormat:=wdFormatPDF
'Close Word template without saving changes
wdDoc.Close savechanges:=False
MsgBox ("PDF files were successfully generated"), vbInformation, "NOTIFICATION"
wdDoc.Quit
End Sub
Untested:
Sub PrintPrivacyPolicyDoc_EN()
Dim objWord As Word.Application, wdDoc As Word.Document
Dim nomArch As String, uf As Long, wArch As String
Dim ws As Worksheet, j As Long, nomFic As String, rutaInf As String
Set ws = ActiveSheet
nomArch = Split(ws.Name, ".")(0)
wArch = ThisWorkbook.Path & "\" & ws.Range("B3").Text & ".dotx"
uf = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
Set objWord = CreateObject("Word.Application")
objWord.DisplayAlerts = wdAlertsNone
objWord.Visible = True
For j = 5 To uf
If Not ws.Rows(j).Hidden Then 'visible rows only
Set wdDoc = objWord.Documents.Open(wArch)
nomFic = nomArch & "_" & ws.Cells(j, "A") & "_" & ws.Range("C3").Text
rutaInf = ThisWorkbook.Path & "\PrivacyPolicy PDFs\" & nomFic & ".pdf"
ReplaceAll wdDoc, "[Company_Name]", ws.Cells(j, "B")
ReplaceAll wdDoc, "[Vat_Number]", ws.Cells(j, "C")
ReplaceAll wdDoc, "[URL_Stay]", ws.Cells(j, "D")
ReplaceAll wdDoc, "[Update_Date]", ws.Cells(j, "E")
If Dir(rutaInf) <> "" Then Kill rutaInf
'Save file with the designated name
wdDoc.SaveAs Filename:=rutaInf, FileFormat:=wdFormatPDF
wdDoc.Close savechanges:=False
End If 'row not hidden
Next j
objWord.Quit 'close Word
End Sub
'Replace all instances of txtFind with txtReplace in doc
Sub ReplaceAll(doc As Word.Document, txtFind As String, txtReplace As String)
With doc.Range.Find
.Text = txtFind
.Replacement.Text = txtReplace
.Replacement.ClearFormatting
.Replacement.Font.Italic = False
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=wdReplaceAll
End With
End Sub
I have seen this asked multiple times but none of the solutions offered have solved my issue- I continue to get this error even though I have used the same code in multiple other applications with no errors. I have included the code below and hope that someone can spot the issue that I am just failing to see!
Sub CreateJobsGraphsPrincipalCategory()
'Initial variables
Dim wbnew As Workbook
Dim wsnew As Worksheet
Dim Datasheet As Worksheet
'Dataset variables
Dim BeneficiaryList(0 To 10000), PrincipalList(0 To 10000), CheckRange As String
Dim NumberRows, RowNumber As Long
Dim Isduplicate, intPrincipal, intStatus, intLineItem As Integer
Dim PrincipalColumn, StatusColumn, LineItemColumn As String
Dim PrincipalRange, StatusRange, LineItemRange As String
Dim PrincipalNumber, BeneficiaryNumber As Integer
'New PivotChart variables
Dim objPivotcache As PivotCache
Dim objPivotTable As PivotTable
Dim bcount As Integer
Dim ProsperatorArray(1 To 25) As String
Dim BusinessNameColumn, BeneficiaryName, BeneficiaryNameFind As String
Dim objPivot As PivotTable, objPivotRange As Range, objChart As Chart
Dim LastColumnNumber As Double
'Setup workbooks
Dim CurrentWorkbook As Workbook
Dim SaveToWorkbook As Workbook
'Stop screen updating and calculating furing processing
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
'Select overall datasheet
Worksheets("DataforPrincipals").Activate
Set Datasheet = ActiveSheet
'Find last column. Start from column 30 as it will not be less than this
LastColumnNumber = 30
LastColumnValue = Datasheet.Cells(1, LastColumnNumber)
While LastColumnValue <> ""
LastColumnNumber = LastColumnNumber + 1
LastColumnValue = Datasheet.Cells(1, LastColumnNumber)
Wend
LastColumnNumber = LastColumnNumber - 1
'LastColumnValue = Datasheet.Cells(1, LastColumnNumber)
LastColumnValue = Getcolumn(LastColumnNumber)
'get last row
LastRowNumber = 1
LastRowRange = "A" & LastRowNumber
LastRowValue = Datasheet.Cells(LastRowNumber, 1)
While LastRowValue <> ""
LastRowNumber = LastRowNumber + 1
LastRowRange = "A" & LastRowNumber
LastRowValue = Datasheet.Cells(LastRowNumber, 1)
Wend
LastRowNumber = LastRowNumber - 1
PivotRange = "A" & "1" & ":" & LastColumnValue & LastRowNumber
'Creating Pivot cache
Set objPivotcache = ActiveWorkbook.PivotCaches.Create(xlDatabase, "'DataforPrincipals'!" & PivotRange)
'Create Arrays for Beneficiaries and Principals
'Get Columns for filtering and checking
PrincipalColumn = FindDataColumnHeading("Principal")
' StatusColumn = FindDataColumnHeading("Status")
LineItemColumn = FindDataColumnHeading("Line Item")
BusinessNameColumn = FindDataColumnHeading("Business Name")
RowNumber = 2
NumberRows = 0
CheckRange = BusinessNameColumn & RowNumber
PrincipalNumber = 1
BeneficiaryNumber = 1
While Datasheet.Range(CheckRange) <> ""
NumberRows = NumberRows + 1
PrincipalRange = PrincipalColumn & RowNumber
' StatusRange = StatusColumn & RowNumber
LineItemRange = LineItemColumn & RowNumber
' If Datasheet.Range(StatusRange) = "Active" Then
If Datasheet.Range(LineItemRange) = "Turnover" Then
BeneficiaryList(BeneficiaryNumber) = Datasheet.Range(CheckRange)
BeneficiaryNumber = BeneficiaryNumber + 1
'Check if principal is in the dataset yet
If RowNumber = 2 Then
PrincipalList(PrincipalNumber) = UCase(Trim(Datasheet.Range(PrincipalRange)))
Else
PrincipalNumber = PrincipalNumber + 1
Isduplicate = 0
For i = 1 To PrincipalNumber
If PrincipalList(i) = UCase(Trim(Datasheet.Range(PrincipalRange))) Then
Isduplicate = 1
End If
Next i
If Isduplicate = 0 Then
PrincipalList(PrincipalNumber) = UCase(Trim(Datasheet.Range(PrincipalRange)))
Else
PrincipalNumber = PrincipalNumber - 1
End If
End If
End If
' End If
RowNumber = RowNumber + 1
CheckRange = BusinessNameColumn & RowNumber
Wend
Set CurrentWorkbook = Application.ActiveWorkbook
' Set wbnew = Workbooks.Add
'wbnew = ActiveWorkbook.Name
CurrentWorkbook.Activate
For i = 1 To PrincipalNumber
PrincipalNameFind = PrincipalList(i)
If PrincipalList(i) <> PrincipalList(i - 1) Then
If InStr(1, PrincipalList(i), "(") > 0 Then
PrincipalName = Left(PrincipalList(i), 25) & 0
Else
PrincipalName = Left(PrincipalList(i), 25)
End If
'Adding new worksheet
Worksheets("DataforPrincipals").Activate
Set wsnew = Worksheets.Add
wsnew.Name = PrincipalName & "JC"
Worksheets(PrincipalName & "JC").Activate
'Creating Pivot table
Set objPivotTable = objPivotcache.CreatePivotTable(wsnew.Range("A1"))
'set Beneficiary row field
'Setting Fields
With objPivotTable
With .PivotFields("Principal")
.Orientation = xlPageField
.CurrentPage = "ALL"
.ClearAllFilters
.CurrentPage = PrincipalNameFind
End With
'set data fields (PI TO, TO)
With .PivotFields("Category")
.Orientation = xlRowField
End With
.AddDataField .PivotFields("PI Total Staff"), "PI Jobs", xlSum
.AddDataField .PivotFields("Current Total Staff"), "Current Jobs", xlSum
.AddDataField .PivotFields("Job Growth"), "Job Growth ", xlSum
With .PivotFields("PI Jobs")
.NumberFormat = "#"
End With
With .PivotFields("Current Jobs")
.NumberFormat = "#"
End With
With .PivotFields("Job Growth ")
.NumberFormat = "#%"
End With
End With
' Access the new PivotTable from the sheet's PivotTables collection.
Set objPivot = ActiveSheet.PivotTables(1)
' Add a new chart sheet.
Set objChart = Charts.Add
' Create a Range object that contains
' all of the PivotTable data, except the page fields.
Set objPivotRange = objPivot.TableRange1
' Specify the PivotTable data as the chart's source data.
With objChart
.ShowAllFieldButtons = False
.SetSourceData objPivotRange
.ChartType = xlColumnClustered
.ApplyLayout (5)
With .ChartTitle
.Text = " Employment Growth performance per Category"
End With
.SeriesCollection(1).HasDataLabels = False
.SeriesCollection(2).HasDataLabels = False
.SeriesCollection(3).HasDataLabels = False
.Axes(xlCategory).HasTitle = False
.DataTable.Select
End With
If InStr(1, PrincipalList(i), "(") > 0 Then
PrincipalName = Left(PrincipalList(i), 25) & 0
Else
PrincipalName = Left(PrincipalList(i), 25)
End If
ActiveSheet.Name = PrincipalName & " JCG"
If Sheetslist = "" Then
Sheetslist = PrincipalName & " JCG"
Else
Sheetslist = Sheetslist & ", " & PrincipalName & " JOBS"
End If
End If
Next i
'Copy to new file
Set CurrentWorkbook = Application.ActiveWorkbook
DirectoryName = Sheets("Run Automated").Range("B1")
For i = 1 To PrincipalNumber
If PrincipalList(i) <> PrincipalList(i - 1) Then
With Worksheets("Run Automated")
NameFileInitial = .Range("B2") & " " & PrincipalList(i) & ".xlsm"
End With
If InStr(1, PrincipalList(i), "(") > 0 Then
PrincipalName = Left(PrincipalList(i), 25) & 0
Else
PrincipalName = Left(PrincipalList(i), 25)
End If
'Set sheets to save
sheet1save = PrincipalName & " TC"
sheet2save = PrincipalName & " TOC"
sheet7save = PrincipalName & "JC"
sheet8save = PrincipalName & " JCG"
Set CurrentWorkbook = Application.ActiveWorkbook
Namefile = DirectoryName & "\" & NameFileInitial
Workbooks.Open Namefile
Set SaveToWorkbook = Application.ActiveWorkbook
Application.DisplayAlerts = False
CurrentWorkbook.Sheets(Array(sheet1save, sheet2save, sheet7save, sheet8save)).Move Before:=SaveToWorkbook.Sheets(1)
ActiveWorkbook.Close (True)
Application.DisplayAlerts = True
CurrentWorkbook.Activate
End If
Next i
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.DisplayAlerts = True
End Sub