.vbs: write protection for header/footer in Word - vbscript

I am currently working on some visual basic scripts (.vbs) for word. I need to find out whether the header/footer is write protected or not. I used following snippet:
Sub main(testAction)
Dim doc 'As Word.Document
Dim paAction 'As Engine.clsParamAction
Dim sAction 'As String
Dim paDocument 'As Engine.clsParamAction
Dim sDocumentName 'As String
Dim paValue 'As Engine.clsParamAction
Set paDocument = testAction.paramAction("Document Name", True)
If paDocument Is Nothing Then
sDocumentName = "#1"
else
sDocumentName = paDocument.inputView.Value
End If
Set doc = WaitForDocument(sDocumentName , lTimeout)
Set paAction = testAction.paramAction("Action", True)
sAction = paAction.inputView.value
Set paValue = testAction.paramAction("Value", True)
select case (lcase(sAction))
case "headersectionisprotected":
paValue.actValue = doc.Sections(1).Headers(2).Range.Sections.Item(1).ProtectedForForms
paValue.HandleActValue
Exit Sub
end select
End Sub
The subroutine is called via Tricentis Tosca - I am sorry I am not able to give a reproducible "standalone" example:
Obviously the command "doc.Sections(1).Headers(2).Range.Sections.Item(1).ProtectedForForms" does not work as expected - the return value is always true, no matter if the header is protected or not.
Note: Tosca is not making the troubles here because I have several other subs integrated like that and all of them are working fine.

Related

To convert string to double in UFT/QTP

I am trying to convert string to double in UFT but It shows the output without decimal point. below is the code for reference.
vStr = "1000000.589765"
msgbox Typename(vStr)
strV1=CDBL(formatNumber(vStr,4))
msgbox Typename(strV1)
print strV1
Output: 1000000589765
Note that without formatNumber, its not working.
Yet another implementation using DotNetFactory. Just an another thought. I am not denying to use CDbl. But worth to give a shot.
'Test Code
Dim strConvertedCode
strConvertedCode = ConvertDataType("1000000.589765","Double")
If strConvertedCode <> null Then
Msgbox strConvertedCode
End If
Public Function ConvertDataType(ByVal SourceData,ByVal ConversionDataType)
'Initialization of variables
Dim objDotNetFactory
Dim strConvertedData : strConvertedData = null
Dim strSystemNamespace
'Determine the destination data type
Select Case UCase(ConversionDataType)
Case "DOUBLE"
strSystemNamespace = "System.Double"
'Implement further for your data types
'Reference https://msdn.microsoft.com/en-us/library/ms228360(v=vs.90).aspx
Case Default
Set objDotNetFactory = DotNetFactory.CreateInstance("System.Int32")
End Select
Set objDotNetFactory = DotNetFactory.CreateInstance(strSystemNamespace)
'Check the dot net factory instance is successful
If Not IsObject(objDotNetFactory) Then
Reporter.ReportEvent micWarning,"Data type convertor","Conversion from String to " & ConversionDataType & " failed, Since DotNetFactory instance was not created."
ConvertDataType = strConvertedData
Exit Function
End If
strConvertedData = objDotNetFactory.Parse(SourceData)
ConvertDataType = strConvertedData
End Function

Converting PPT file to PDF

I have a macro which opens a PowerPoint file stored on the workbook and then modifies it using the below code
Set PApp = CreateObject("PowerPoint.Application")
PApp.Visible = True
Pth = ThisWorkbook.Path
ErrorPopUp = True
Dim TsyTemplate As Object
Set TsyTemplate = ThisWorkbook.Sheets("Report Templates").OLEObjects(“Report 1”)
TsyTemplate.Copy
Sheets("Version Control").Paste
Set TsyTemplate = ThisWorkbook.Sheets("Book 1").OLEObjects(1)
TsyTemplate.Verb Verb:=xlOpen
Set TsyTemplate = Nothing
Set PPres = PApp.ActivePresentation
This works fine however I want to add some code which then converts the open PowerPoint file into a PDF file. I would prefer it to just convert it without saving it somewhere but I don't believe this is possible so I am using he below code to save it as a PDF FILE
PDFName = ActiveWorkbook.Path & "/test.pdf"
PPres.ExportAsFixedFormat Path:=PDFName, FixedFormatType:=ppFixedFormatTypePDF, RangeType:=ppPrintSelection
This isn't working though as I get the error message "type mismatch"
Does anyone have any suggestions as to what I am doing wrong.
Thanks
Full code:
Global PApp As Object
Global PPres As Object
Global PPTFileName As String
Global ppFixedFormatTypePDF As Long
Global ppPrintSelection As Long
Sub Test_Printing_To_PDF()
Set PApp = CreateObject("PowerPoint.Application")
PApp.Visible = True
Pth = ThisWorkbook.Path
ErrorPopUp = True
Dim TsyTemplate As Object
Set TsyTemplate = ThisWorkbook.Sheets("Report Templates").OLEObjects("Report 1")
TsyTemplate.Copy
Sheets("Version Control").Paste
Set TsyTemplate = ThisWorkbook.Sheets("Version Control").OLEObjects(1)
TsyTemplate.Verb Verb:=xlOpen
Set TsyTemplate = Nothing
Set PPres = PApp.ActivePresentation
PPres.Slides(1).Shapes("Presentation_Title").TextFrame.TextRange.Text = "Test printing code"
ppFixedFormatTypePDF = 2
ppPrintSelection = 2
PDFName = ActiveWorkbook.Path & "/test.pdf"
PPres.ExportAsFixedFormat Path:=PDFName, FixedFormatType:=ppFixedFormatTypePDF, RangeType:=ppPrintSelection
End Sub
I removed some of your Excel code so that I could try this here; since it seems to have nothing to do with the PDF export from PPT, shouldn't make any difference. New (working) code below with comments:
Option Explicit
Global PApp As Object
Global PPres As Object
Global PPTFileName As String
Global ppFixedFormatTypePDF As Long
Global ppPrintSelection As Long
Const ppSaveAsPDF As Long = 32
Sub Test_Printing_To_PDF()
' Always include Option Explicit and DIM all variables
Dim Pth As String
Dim ErrorPopUp As Boolean
Dim PDFName As String
Set PApp = CreateObject("PowerPoint.Application")
PApp.Visible = True
Pth = ThisWorkbook.Path
ErrorPopUp = True
' Just invoking PowerPoint doesn't necessarily create a presentation.
' You need to add one (or open an existing one)
Set PPres = PApp.presentations.Add
' And creating a new presentation doesn't necessarily add slides so:
PPres.slides.Add 1, 1
' Unless you've opened a presentation that happens to have a shape named
' Presentation_Title on the first slide, this will fail:
'PPres.slides(1).Shapes("Presentation_Title").TextFrame.TextRange.Text = "Test printing code"
' So I've changed it to this:
PPres.slides(1).Shapes(1).TextFrame.TextRange.Text = "Test printing code"
' / isn't a valid character:
'PDFName = ActiveWorkbook.Path & "/test.pdf"
' so I changed it to this:
PDFName = ActiveWorkbook.Path & "\test.pdf"
' And there are all sorts of reports all over the net about
' the Export routine being buggy. Substitute this and it works:
PPres.SaveAs PDFName, ppSaveAsPDF
End Sub

AutoCAD Architecture Vision Tools in AutoCAD

I have both AutoCAD and AutoCAD Architecture installed on my system. AutoCAD Architecture has a tab called Vision Tools with a nifty command called Display By Layer to set the display order of objects in accordance with the layers of the drawing. Is there anyway to add this tab or use this command in AutoCAD?
Not sure if you're looking for a built-in feature or APIs for it.
For a built in feature, check the DRAWORDER command. For an API/programming approach, check the respective DrawOrderTable method. See below:
Update: please also check this 3rd party tool: DoByLayer.
[CommandMethod("SendToBottom")]
public void commandDrawOrderChange()
{
Document activeDoc
= Application.DocumentManager.MdiActiveDocument;
Database db = activeDoc.Database;
Editor ed = activeDoc.Editor;
PromptEntityOptions peo
= new PromptEntityOptions("Select an entity : ");
PromptEntityResult per = ed.GetEntity(peo);
if (per.Status != PromptStatus.OK)
{
return;
}
ObjectId oid = per.ObjectId;
SortedList<long, ObjectId> drawOrder
= new SortedList<long, ObjectId>();
using (Transaction tr = db.TransactionManager.StartTransaction())
{
BlockTable bt = tr.GetObject(
db.BlockTableId,
OpenMode.ForRead
) as BlockTable;
BlockTableRecord btrModelSpace =
tr.GetObject(
bt[BlockTableRecord.ModelSpace],
OpenMode.ForRead
) as BlockTableRecord;
DrawOrderTable dot =
tr.GetObject(
btrModelSpace.DrawOrderTableId,
OpenMode.ForWrite
) as DrawOrderTable;
ObjectIdCollection objToMove = new ObjectIdCollection();
objToMove.Add(oid);
dot.MoveToBottom(objToMove);
tr.Commit();
}
ed.WriteMessage("Done");
}
With some help from VBA it might look by this. Note i did not add fancy listbox code. I just show the worker and how to list layers. The trivial Code to add things to a listbox on a form and how to sort / rearrange listbox items can be found on any excel / VBA forum on the web . Or you just uses a predefined string like in the example. To get VBA to work download and install the acc. VBA Enabler from autocad. It is free.
'select all items on a layer by a filter
Sub selectALayer(sset As AcadSelectionSet, layername As String)
Dim filterType As Variant
Dim filterData As Variant
Dim p1(0 To 2) As Double
Dim p2(0 To 2) As Double
Dim grpCode(0) As Integer
grpCode(0) = 8
filterType = grpCode
Dim grpValue(0) As Variant
grpValue(0) = layername
filterData = grpValue
sset.Select acSelectionSetAll, p1, p2, filterType, filterData
Debug.Print "layer", layername, "Entities: " & str(sset.COUNT)
End Sub
'bring items on top
Sub OrderToTop(layername As String)
' This example creates a SortentsTable object and
' changes the draw order of selected object(s) to top.
Dim oSset As AcadSelectionSet
Dim oEnt
Dim i As Integer
Dim setName As String
setName = "$Order$"
'Make sure selection set does not exist
For i = 0 To ThisDrawing.SelectionSets.COUNT - 1
If ThisDrawing.SelectionSets.ITEM(i).NAME = setName Then
ThisDrawing.SelectionSets.ITEM(i).DELETE
Exit For
End If
Next i
setName = "tmp_" & time()
Set oSset = ThisDrawing.SelectionSets.Add(setName)
Call selectALayer(oSset, layername)
If oSset.COUNT > 0 Then
ReDim arrObj(0 To oSset.COUNT - 1) As ACADOBJECT
'Process each object
i = 0
For Each oEnt In oSset
Set arrObj(i) = oEnt
i = i + 1
Next
End If
'kills also left over selectionset by programming mistakes....
For Each selectionset In ThisDrawing.SelectionSets
selectionset.delete_by_layer_space
Next
On Error GoTo Err_Control
'Get an extension dictionary and, if necessary, add a SortentsTable object
Dim eDictionary As Object
Set eDictionary = ThisDrawing.modelspace.GetExtensionDictionary
' Prevent failed GetObject calls from throwing an exception
On Error Resume Next
Dim sentityObj As Object
Set sentityObj = eDictionary.GetObject("ACAD_SORTENTS")
On Error GoTo 0
If sentityObj Is Nothing Then
' No SortentsTable object, so add one
Set sentityObj = eDictionary.AddObject("ACAD_SORTENTS", "AcDbSortentsTable")
End If
'Move selected object(s) to the top
sentityObj.MoveToTop arrObj
applicaTION.UPDATE
Exit Sub
Err_Control:
If ERR.NUMBER > 0 Then MsgBox ERR.DESCRIPTION
End Sub
Sub bringtofrontbylist()
Dim lnames As String
'predefined layer names
layer_names = "foundation bridge road"
Dim h() As String
h = split(layernames)
For i = 0 To UBound(h)
Call OrderToTop(h(i))
Next
End Sub
'in case you want a fancy form here is how to get list / all layers
Sub list_layers()
Dim LAYER As AcadLayer
For Each LAYER In ThisDrawing.LAYERS
Debug.Print LAYER.NAME
Next
End Sub
to make it run put the cursor inside the VBA IDE inside the code of list_layers andpress F5 or choose it from the VBA Macro list.

csv file import to access database using vba

Im using visual basic and visual studio 2010.
I researched on importing csv files to access database and I found this generic codes. The problem is, I'm really new in visual basic. I declared the variables but I got the error: "Declaration expected".. and the Do while and Loop are having an error which is: "Statement cannot appear outside of a method
Public Class Form1
Dim strPathFile As String
Dim strFile As String
Dim strPath As String
Dim strTable As String
Dim blnHasFieldNames As Boolean
blnHasFieldNames = True
strPath = "C:\Users\vissia18\Desktop\ReportDB\"
strTable = "Report"
strFile = Dir(strPath & "*.csv")
Do While Len(strFile) > 0
strPathFile = strPath & strFile
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
strTable, strPathFile, blnHasFieldNames
strFile = Dir()
Loop
End Class
The first thing I see is that no method or subroutine has been declared.
That is essential.
How about declaring a Main like this:
Public Class Form1
Sub Main()
Dim strPathFile As String
Dim strFile As String
...
End Sub
End Class
This will give your application a staring point.
May I suggest MSDN - Microsoft Developer Network - specifically the video walk through labelled "Visual Basic Fundamentals: Development for Absolute Beginners".

Opening Word from VBScript hangs, can't figure out why

I'm not really a programmer by trade, so forgive me if I'm not aware of any standard debugging tools.
I have what I thought was a very simple VBScript (just a txt file saved with a .vbs extension):
Const wdDoNotSaveChanges = 0
Const wdRevisionsViewFinal = 0
Const wdFormatPDF = 17
Dim arguments
Set arguments = WScript.Arguments
Function DOC2PDF(sDocFile)
Dim fso ' As FileSystemObject
Dim wdo ' As Word.Application
Dim wdoc ' As Word.Document
Dim wdocs ' As Word.Documents
Set fso = CreateObject("Scripting.FileSystemObject")
sDocFile = fso.GetAbsolutePathName(sDocFile)
sPdfFile = fso.GetParentFolderName(sDocFile) + "\" + fso.GetBaseName(sDocFile) + ".pdf"
Set wdo = CreateObject("Word.Application")
Set wdocs = wdo.Documents
Set wdoc = wdocs.Open(sDocFile)
if fso.FileExists(sPdfFile) Then
fso.DeleteFile sPdfFile, True
End If
Set wview = wdoc.ActiveWindow.View
wview.ShowRevisionsAndComments = False
wview.RevisionsView = wdRevisionsViewFinal
wdoc.SaveAs sPdfFile, wdFormatPDF
wdo.Quit wdDoNotSaveChanges
Set fso = Nothing
Set wdo = Nothing
End Function
however, the following line is causing huge grief:
Set wdoc = wdocs.Open(sDocFile)
Sometimes the Word ActiveX object just freezes at this step. I've verified this by some super-simple debugging by putting a WriteLine after each line and seeing where it stops.
Word just sits there consuming 100% CPU, and the script never gets past that step.
How can I go about debugging to find out what the hell is going on with the Word ActiveX object and why it's just hanging and never returning?
Word might be waiting for a prompt from you. I would make Word visible and see if you can visually see what the problem is:
Set wdo = CreateObject("Word.Application")
'if memory serves, this should make Word visible
wdo.Visible = true
Set wdocs = wdo.Documents

Resources