Programmatically change "Don't add space between paragraphs of the same style" - vba

I'm trying to programmatically change "Don't add space between paragraphs of the same style." To approach the problem, I recorded a macro during which I opened the Paragraph dialog box (Page Layout > Paragraph), checked the checkbox (don't add space) and a macro during which I unchecked the checkbox (add space). Neither affects "Don't add space between paragraphs of the same style" . . . and they have identical code:
Sub AddSpaceBetweenParagraphsOfSameStyle()
'
' AddSpaceBetweenParagraphsOfSameStyle Macro
' Add space between paragraphs of the same style.
'
With Selection.ParagraphFormat
.LeftIndent = InchesToPoints(0.5)
.RightIndent = InchesToPoints(0)
.SpaceBefore = 12
.SpaceBeforeAuto = False
.SpaceAfter = 12
.SpaceAfterAuto = False
.LineSpacingRule = wdLineSpaceMultiple
.LineSpacing = LinesToPoints(1)
.Alignment = wdAlignParagraphLeft
.WidowControl = True
.KeepWithNext = False
.KeepTogether = False
.PageBreakBefore = False
.NoLineNumber = False
.Hyphenation = True
.FirstLineIndent = InchesToPoints(-0.25)
.OutlineLevel = wdOutlineLevelBodyText
.CharacterUnitLeftIndent = 0
.CharacterUnitRightIndent = 0
.CharacterUnitFirstLineIndent = 0
.LineUnitBefore = 0
.LineUnitAfter = 0
.MirrorIndents = False
.TextboxTightWrap = wdTightNone
End With
End Sub
Sub RemoveSpaceBetweenParagraphsOfSameStyle()
'
' RemoveSpaceBetweenParagraphsOfSameStyle Macro
' Remove space between paragraphs of the same style.
'
With Selection.ParagraphFormat
.LeftIndent = InchesToPoints(0.5)
.RightIndent = InchesToPoints(0)
.SpaceBefore = 12
.SpaceBeforeAuto = False
.SpaceAfter = 12
.SpaceAfterAuto = False
.LineSpacingRule = wdLineSpaceMultiple
.LineSpacing = LinesToPoints(1)
.Alignment = wdAlignParagraphLeft
.WidowControl = True
.KeepWithNext = False
.KeepTogether = False
.PageBreakBefore = False
.NoLineNumber = False
.Hyphenation = True
.FirstLineIndent = InchesToPoints(-0.25)
.OutlineLevel = wdOutlineLevelBodyText
.CharacterUnitLeftIndent = 0
.CharacterUnitRightIndent = 0
.CharacterUnitFirstLineIndent = 0
.LineUnitBefore = 0
.LineUnitAfter = 0
.MirrorIndents = False
.TextboxTightWrap = wdTightNone
End With
End Sub
The code produced by the macro recorder is long, so I reduced it to a minimal version that I've verified also fails to affect "Don't add space between paragraphs of the same style":
Sub AddSpaceBetweenParagraphsOfSameStyle()
'
' AddSpaceBetweenParagraphsOfSameStyle Macro
' Add space between paragraphs of the same style.
'
End Sub
Sub RemoveSpaceBetweenParagraphsOfSameStyle()
'
' RemoveSpaceBetweenParagraphsOfSameStyle Macro
' Remove space between paragraphs of the same style.
'
End Sub
I looked at the documentation for ParagraphFormat and searched for a relevant property but found nothing that works. How can I programmatically change "Don't add space between paragraphs of the same style"?

This property is connected with Style, not with Paragraph (which suggests window title where you set this property). This is code which you look for:
ActiveDocument.Styles("Normal").NoSpaceBetweenParagraphsOfSameStyle = False
ActiveDocument.Styles("Normal").NoSpaceBetweenParagraphsOfSameStyle = True

The macro recorder recognizes changing spacing but not "Don't add space between paragraphs of the same style" (Page Layout > Paragraph). To change paragraph formatting without modifying a built-in style (or creating a new style), I can use Selection.Style:
Selection.Style.NoSpaceBetweenParagraphsOfSameStyle = False
or fall back to the built-in dialog:
With Dialogs(wdDialogFormatParagraph)
.Before = 12
.After = 12
.NoSpaceBetweenParagraphsOfSameStyle = False
.Execute
End With

winword.ActiveDocument.Styles["Normal"].NoSpaceBetweenParagraphsOfSameStyle = true;
winword.ActiveDocument.Styles["List Paragraph"].NoSpaceBetweenParagraphsOfSameStyle = false;
On word doc press Alt+Ctl+Shift+S to check all the styles

If anyone stumbles on this and is looking for a C# example, this is what worked for me. Hope it helps someone else.
string signaturesPath = Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + #"\Microsoft\Signatures\";
Directory.CreateDirectory(signaturesPath + "Test");
Word.Application oWord = new Word.Application();
//oWord.Visible = true;
Word.Document oDoc = oWord.Documents.Add();
//Insert a paragraph at the beginning of the document.
Word.Paragraph paragraph1 = oDoc.Content.Paragraphs.Add();
object oStyleName1 = Word.WdBuiltinStyle.wdStyleNormal;
//NoSpaceBetweenParagraphsOfSameStyle set on style then assign to doc
oWord.ActiveDocument.Styles[oStyleName1].NoSpaceBetweenParagraphsOfSameStyle = true;
//Setting style on paragraph here
paragraph1.Format.set_Style(oStyleName1);
paragraph1.Range.Font.Bold = 1;
paragraph1.Range.InsertAfter("Testing 123");
//Save as htm
object htmlFormat = (int)Word.WdSaveFormat.wdFormatFilteredHTML;
oDoc.SaveAs2(signaturesPath + #"\test.htm", htmlFormat);
oWord.Quit();

Related

What is lacking in my VBA code? Looking to have multiple checkboxes that when one is selected, it hides all other rows

Brand new to coding junk in VBA for Microsoft Word. I have a table with 12 rows and I want to place a standard content control checkbox next to each row, and when any given checkbox is checked, the other rows disappear.
Currently I've had good luck at this with purely text, but trying to bookmark to hide an entire row of a table only seems to work for the very first checkbox. (Sorry if my code is more complicated than it needs to be. I also skipped pasting all of the code since the other 10 lines are the same, so the final 12 End Ifs are necessary):
Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)
Dim cc As ContentControl
For Each cc In ActiveDocument.ContentControls
If cc.Title = "impact" Then
If cc.Checked = True Then
ActiveDocument.Bookmarks("bfganalytical").Range.Font.Hidden = True
ActiveDocument.Bookmarks("EA").Range.Font.Hidden = True
ActiveDocument.Bookmarks("fascia1").Range.Font.Hidden = True
ActiveDocument.Bookmarks("fascia2").Range.Font.Hidden = True
ActiveDocument.Bookmarks("grille1").Range.Font.Hidden = True
ActiveDocument.Bookmarks("grille2").Range.Font.Hidden = True
ActiveDocument.Bookmarks("shutter1").Range.Font.Hidden = True
ActiveDocument.Bookmarks("shutter2").Range.Font.Hidden = True
ActiveDocument.Bookmarks("liner").Range.Font.Hidden = True
ActiveDocument.Bookmarks("license").Range.Font.Hidden = True
ActiveDocument.Bookmarks("lamp1").Range.Font.Hidden = True
ActiveDocument.Bookmarks("lamp2").Range.Font.Hidden = True
ActiveDocument.Bookmarks("blank").Range.Font.Hidden = True
ActiveDocument.Bookmarks("impact").Range.Font.Hidden = False
ActiveDocument.Bookmarks("beamanalytical").Range.Font.Hidden = False
Else: ActiveDocument.Bookmarks("impact").Range.Font.Hidden = False
ActiveDocument.Bookmarks("bfganalytical").Range.Font.Hidden = False
ActiveDocument.Bookmarks("EA").Range.Font.Hidden = False
ActiveDocument.Bookmarks("fascia1").Range.Font.Hidden = False
ActiveDocument.Bookmarks("fascia2").Range.Font.Hidden = False
ActiveDocument.Bookmarks("grille1").Range.Font.Hidden = False
ActiveDocument.Bookmarks("grille2").Range.Font.Hidden = False
ActiveDocument.Bookmarks("shutter1").Range.Font.Hidden = False
ActiveDocument.Bookmarks("shutter2").Range.Font.Hidden = False
ActiveDocument.Bookmarks("liner").Range.Font.Hidden = False
ActiveDocument.Bookmarks("license").Range.Font.Hidden = False
ActiveDocument.Bookmarks("lamp1").Range.Font.Hidden = False
ActiveDocument.Bookmarks("lamp2").Range.Font.Hidden = False
ActiveDocument.Bookmarks("beamanalytical").Range.Font.Hidden = False
ActiveDocument.Bookmarks("blank").Range.Font.Hidden = False
End If
Exit Sub
Else: If cc.Title = "license" Then
If cc.Checked = True Then
ActiveDocument.Bookmarks("beamanalytical").Range.Font.Hidden = True
ActiveDocument.Bookmarks("impact").Range.Font.Hidden = True
ActiveDocument.Bookmarks("fascia1").Range.Font.Hidden = True
ActiveDocument.Bookmarks("fascia2").Range.Font.Hidden = True
ActiveDocument.Bookmarks("grille1").Range.Font.Hidden = True
ActiveDocument.Bookmarks("grille2").Range.Font.Hidden = True
ActiveDocument.Bookmarks("shutter1").Range.Font.Hidden = True
ActiveDocument.Bookmarks("shutter2").Range.Font.Hidden = True
ActiveDocument.Bookmarks("liner").Range.Font.Hidden = True
ActiveDocument.Bookmarks("license").Range.Font.Hidden = False
ActiveDocument.Bookmarks("lamp1").Range.Font.Hidden = True
ActiveDocument.Bookmarks("lamp2").Range.Font.Hidden = True
ActiveDocument.Bookmarks("blank2").Range.Font.Hidden = True
ActiveDocument.Bookmarks("blank3").Range.Font.Hidden = True
ActiveDocument.Bookmarks("EA").Range.Font.Hidden = True
ActiveDocument.Bookmarks("bfganalytical").Range.Font.Hidden = False
Else: ActiveDocument.Bookmarks("impact").Range.Font.Hidden = False
ActiveDocument.Bookmarks("bfganalytical").Range.Font.Hidden = False
ActiveDocument.Bookmarks("EA").Range.Font.Hidden = False
ActiveDocument.Bookmarks("fascia1").Range.Font.Hidden = False
ActiveDocument.Bookmarks("fascia2").Range.Font.Hidden = False
ActiveDocument.Bookmarks("grille1").Range.Font.Hidden = False
ActiveDocument.Bookmarks("grille2").Range.Font.Hidden = False
ActiveDocument.Bookmarks("shutter1").Range.Font.Hidden = False
ActiveDocument.Bookmarks("shutter2").Range.Font.Hidden = False
ActiveDocument.Bookmarks("liner").Range.Font.Hidden = False
ActiveDocument.Bookmarks("license").Range.Font.Hidden = False
ActiveDocument.Bookmarks("lamp1").Range.Font.Hidden = False
ActiveDocument.Bookmarks("lamp2").Range.Font.Hidden = False
ActiveDocument.Bookmarks("beamanalytical").Range.Font.Hidden = False
ActiveDocument.Bookmarks("blank2").Range.Font.Hidden = False
ActiveDocument.Bookmarks("blank3").Range.Font.Hidden = False
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
Next
End Sub
Assuming that the content control Title is the same as the bookmark name you can try this simplified version of your code.
Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)
Dim cc As ContentControl
For Each cc In ActiveDocument.ContentControls
If ActiveDocument.Bookmarks.Exists(cc.Title) Then
ActiveDocument.Bookmarks(cc.Title).Range.Font.Hidden = cc.Checked
End If
Next cc
End Sub
EDIT:
The issue you have with your original code is that it will only allow one row to be hidden.
To make your solution work you need to query the checked status of the corresponding content control for each bookmark. Your best option to achieve that is to ensure that the bookmark name matches either cc.Title or cc.Tag, otherwise you are back to complex and unwieldy code.
You actually don't need anything more complicated than:
Private Sub Document_ContentControlOnExit(ByVal CCtrl As ContentControl, Cancel As Boolean)
With CCtrl
If .Range.Information(wdWithInTable) = True Then
If .Checked = True Then
.Range.Tables(1).Range.Font.Hidden = True
.Range.Rows(1).Range.Font.Hidden = False
Else
.Range.Tables(1).Range.Font.Hidden = False
End If
End If
End With
End Sub
Looping through all the content controls is quite unnecessary. You don't even need any titles or bookmarks.

Word VBA: Have any character styles been assigned within the selection?

Is there any simple and universal way to find out whether or not any character style has been assigned within the selected text?
Presently I'm using a function, but it is not independent of the MS Word language version:
Function AnyCharacterStyleAssigned()
'elicit the name of the default paragraph font
V_AppLang = Application.Language
If V_AppLang = 1031 Then
Vst_Default = "Absatz-Standardschriftart"
ElseIf V_AppLang = 1045 Then
Vst_Default = "Domy" & ChrW(347) & "lna czcionka akapitu"
ElseIf V_AppLan = 1033 Then
Vst_Default = "Default Paragraph Font"
Else
MsgBox prompt:="this script doesn't work for this language version of Word", Buttons:=vbOKOnly
End
End If
'search for the default paragraph font within the selection range
Set R_Range = Selection.Range
R_Range.Find.ClearFormatting
R_Range.Find.Style = Vst_Default
R_Range.Find.Execute findtext:="", Forward:=True, Wrap:=wdFindStop, Format:=True
AnyCharacterStyleAssigned = IIf(R_Range.Start >= Selection.End, False, True)
End Function
Just use built-in style constant:
Function AnyCharacterStyleAssigned()
'search for the default paragraph font within the selection range
Set R_Range = Selection.Range
R_Range.Find.ClearFormatting
R_Range.Find.Style = ActiveDocument.Styles(wdStyleDefaultParagraphFont)
R_Range.Find.Execute findtext:="", Forward:=True, Wrap:=wdFindStop, Format:=True
AnyCharacterStyleAssigned = IIf(R_Range.Start >= Selection.End, False, True)
End Function
A better test would be the following. The code you have, if the selection doesn't have the style, the selection never changes, so you will always have a True case.
Public Sub StyleTest()
Dim R_Range As Range
Set R_Range = Selection.Range
R_Range.Find.ClearFormatting
R_Range.Find.Style = "Strong"
Dim AnyCharacterStyleAssigned As Boolean
AnyCharacterStyleAssigned = False
If R_Range.Find.Execute(Forward:=True, Wrap:=wdFindStop, Format:=True) = True Then
R_Range.Select
AnyCharacterStyleAssigned = True
End If
End Sub

How do I show multiple legends on a VB.Net Chart

My code creates a MS Chart with one or more ChartAreas and I want to have a separate legend for each ChartArea
My code is as below:
For tblNum = 0 To (dsData.Tables.Count - 1)
tblName = dsData.Tables(tblNum).TableName
caTag = dtReport.Rows(tblNum).Item("caTag")
If (dtReport.Rows(tblNum).Item("CAnum") > CAnum) Then
CAnum = dtReport.Rows(tblNum).Item("CAnum")
myChart.ChartAreas.Add(caTag)
myChart.Legends.Add(caTag)
With myChart.Legends(caTag)
.Docking = Docking.Bottom
.DockedToChartArea = caTag
.IsDockedInsideChartArea = False
.TableStyle = LegendTableStyle.Wide
.Alignment = StringAlignment.Center
.Enabled = True
End With
If (caCount > 1) Then
CAindex += 1
myChart.Titles.Add(caTag)
With myChart.Titles(CAindex)
.Docking = Docking.Top
.DockedToChartArea = caTag
.IsDockedInsideChartArea = False
.Alignment = ContentAlignment.TopCenter
.Font = New System.Drawing.Font("Times New Roman", 14, FontStyle.Bold)
.Text = caTag
End With
End If
Else
myChart.Legends(caTag).Enabled = True
End If
However when I run the code only a single Legend is visible containing all series from both ChartAreas as below:
Legend-1.jpg
Can anyone help me please ?
I have found the answer to my own question.
I needed to assign the correct legend to each series as follows:
myChart.Series(tblName).Legend = caTag
Now both legends are shown with the appropriate series names

Need to append data to the next blank row instead of creating data in a new worksheet

I am trying to download the historical stock prices from moneycontrol.com. Here is the code I have...the current code extracts data from each webpage and pastes into a new worksheet each time.
But, I would like to append data to the next blank row instead of creating data in a new worksheet. Can someone please help me with this?
Private Const URL_TEMPLATE As String = "URL;http://www.moneycontrol.com/stocks/hist_stock_result.php?sc_id=RI&pno={0}&hdn=daily&fdt=2000-01-01&todt=2015-12-31"
Private Const NUMBER_OF_PAGES As Byte = 1
Sub DataDownload()
Dim page As Byte
Dim queryTableObject As QueryTable
Dim url As String
For page = 1 To NUMBER_OF_PAGES
url = VBA.Strings.Replace(URL_TEMPLATE, "{0}", page)
Set queryTableObject = ActiveSheet.QueryTables.Add(Connection:=url, Destination:=ThisWorkbook.Worksheets.Add.[a1])
queryTableObject.FieldNames = True
queryTableObject.RowNumbers = False
queryTableObject.FillAdjacentFormulas = False
queryTableObject.PreserveFormatting = True
queryTableObject.RefreshOnFileOpen = True
queryTableObject.BackgroundQuery = True
queryTableObject.RefreshStyle = xlOverwriteCells
queryTableObject.SavePassword = False
queryTableObject.SaveData = False
queryTableObject.AdjustColumnWidth = False
queryTableObject.RefreshPeriod = 0
queryTableObject.WebSelectionType = xlSpecifiedTables
queryTableObject.WebFormatting = xlWebFormattingNone
queryTableObject.WebTables = "4"
queryTableObject.WebPreFormattedTextToColumns = True
queryTableObject.WebConsecutiveDelimitersAsOne = True
queryTableObject.WebSingleBlockTextImport = True
queryTableObject.WebDisableDateRecognition = True
queryTableObject.WebDisableRedirections = True
queryTableObject.Refresh BackgroundQuery:=False
Next page
End Sub
Not tested but try adding this lines:
Dim ws As Worksheet
Set ws = Thisworkbook.Sheets("SheetName") ' change to your actual sheetname
Then change this line:
Set queryTableObject = ActiveSheet.QueryTables.Add(Connection:=url, _
Destination:=ThisWorkbook.Worksheets.Add.[a1])
to this line:
Set queryTableObject = ws.QueryTables.Add(Connection:=URL, _
Destination:=ws.Range("A:A").Find("*", , , , , xlPrevious).Offset(1, 0))
This way, data will be added on the sheet you specified always and at the first blank row.

Disable cell-border highlight DataGridView

I'm trying to disable the border around a cell when selected! (The black rectangle, not the blue background).
Is that possible?
this is my grid initialization code (maybe will help):
With DBGrid
.RowHeadersVisible = False
.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing
.RowTemplate.Height = internal_RowHeight
' Set property values appropriate for read-only display and
' limited interactivity.
.AllowUserToAddRows = False
.AllowUserToDeleteRows = False
.AllowUserToOrderColumns = False
.ReadOnly = True
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.AllowUserToResizeColumns = False
.AllowUserToResizeRows = False
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None
' Set the row height
.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing
.ColumnHeadersHeight = internal_RowHeight
.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing
' Set the selection background color for all the cells.
.DefaultCellStyle.BackColor = internal_BackColor
.DefaultCellStyle.ForeColor = internal_ForeColor
.DefaultCellStyle.SelectionBackColor = internal_BackColorSel
.DefaultCellStyle.SelectionForeColor = internal_ForeColorSel
' Set RowHeadersDefaultCellStyle.SelectionBackColor so that its default
' value won't override DataGridView.DefaultCellStyle.SelectionBackColor.
.RowHeadersDefaultCellStyle.SelectionBackColor = Color.Empty
.RowsDefaultCellStyle.BackColor = Color.Empty
' Set the row and column header styles.
.ColumnHeadersDefaultCellStyle.ForeColor = Color.White
.ColumnHeadersDefaultCellStyle.BackColor = Color.Black
End With
Since you want to disable the active cell, I would assume you only intend to use the grid as a way to select a row and not edit the contents.
In that case, use the following settings:
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
DataGridView1.ReadOnly = True