Set Range to be specific lines within a cell, Microsoft VBA - vba

I am working with a word template document that extensively uses tables to separate values. This has been great for most of my VBA code, as it makes it very simple to set values where I need to make edits. However, there is one place, in the header, where a single cell contains three lines of text. I need to set the value of JUST the first two lines in this cell.
QUESTION:
How do you set the value of JUST the first two lines of text in a given cell? Or, more broadly, can you set Range to be one line within a cell?
What I have right now, which sets Range as the whole cell and sets the value as "NEW TEXT":
ActiveDocument.PageSetup.DifferentFirstPageHeaderFooter = True
With ActiveDocument.Sections(1).Headers(wdHeaderFooterFirstPage)
.Range.Tables(1).Cell(1, 2).Range.Text = "NEW TEXT"
End With
Thank you for any expertise you can lend me.

To replace (eg) the second line:
With ActiveDocument.Sections(1).Headers(wdHeaderFooterFirstPage)
.Range.Tables(1).Cell(1, 2).Range.Paragraphs(2).Range.Text = "NEW TEXT" & vbLf
End With

Related

Scanning through lists in VBA and adding each hit in the same cell

I have been leveraging for the past several months a couple of lines of code in VBA which with the help of the stackoverflow community I was able to adjust as needed (link Looping and scanning a list of e.g., 200 strings against a column with string data (Excel, VBA, Macros)). Essentially, the code scans row by row through a list of pre-defined keywords against a range of data highlighting possible hits in an adjacent empty column/cell. For example, if my range/column contained "DOG ABC LLC" and my keyword list/array contained "ABC" the macro helped easily highlight the hit in another column by displaying it.
I have noticed one issue with this method that often more than one keyword hit could occur. For example, I can have an array containing both "ABC" and "DOG" as separate keywords. The current loop in place sadly only factors in the first hit apparently and then moves on. I was wondering whether there is an easy way of adjusting the code so that one could add all possible hits into a cell after a comma or space. Therefore instead of seeing just "DOG" or "ABC", one could clearly see that there were 2 hits "ABC , DOG". Here is the code I have been using thus far:
Dim wordsArray() As Variant
wordsArray = Worksheets("Keywords").Range("B2:B439").Value
Dim word As Variant
Dim cell As Range
For Each cell In Worksheets("Normalized").Range("J2:J49010")
For Each word In wordsArray
If InStr(cell.Value, word) > 0 Then
cell.Offset(0, -1).Value = word
End If
Next word
Next cell
Thank you in advance for advice!

How do I hide select text in excel (getting weird cells with conditional formatting)

How do hide cells that contain text in excel? These cells I am manually entering numbered data into them. I'd like them to be invisible when containing SetNumber but when I enter data manually, the data is visible.
I have seen a number of vba solutions and this solution which did not work. My question is how do I hide columns A, B and C which all contain SetNumber?
I have used conditional formatting but for some reason the output appears very un-natural. Is there a simple alternative?
To complete my comment above, you can do (in VBA):
Dim celltxt As String
celltxt = ActiveSheet.Range("A1").Text
If InStr(1, celltxt, "SetNumber") Then
Range("A:A").EntireColumn.Hidden = True
EndIf
To hide Column A based upon the contents of cell A1. You should be able to modify this to suit your needs.

Using VBA in Word 2010 to change column widths in a table

I am just getting started with VBA, using my old copy of Word 2010. I want to resize two of the columns in a three column table and format the text that is in the columns. This code was generated by Word's macro recorder:
Selection.ConvertToTable Separator:=wdSeparateByCommas, NumColumns:=3, _
NumRows:=14, AutoFitBehavior:=wdAutoFitContent
With Selection.Tables(1)
.Style = "Table Grid"
.ApplyStyleHeadingRows = True
.ApplyStyleLastRow = False
.ApplyStyleFirstColumn = True
.ApplyStyleLastColumn = False
End With
Selection.Cells.VerticalAlignment = wdCellAlignVerticalCenter
Now I want the first two columns to be 1.3 inches wide and the third column to be 5.1 inches wide. Then I want to change the formatting of the text in the third column to increase the font size. The macro recorder doesn't seem to record when I resize columns. Any suggestions as to how to edit this code?
Controlling tables is rather complicated. Word does much of it the way it sees fit, but if you use VBA you must take control. It really isn't desirable that you should make your life even more miserable by invoking the Selection object. Try and make your object the table itself, for example, like this.
Dim Tbl As Table
Set Tbl = ActiveDocument.Tables.Add(Range:=Selection.Range, _
NumRows:=14, _
NumColumns:=3, _
DefaultTableBehavior:=wdWord8TableBehavior, _
AutoFitBehavior:=wdAutoFitFixed)
' wdWord8TableBehavior = doesn't change table size to match content
The table will be inserted following the selection. You may want to collapse your selection range before running this code. But now that you have a table object you can format it to your heart's content without selecting anything. There are dozens of properties. One of them which you will want to determine is Tbl.PreferredWidth = InchesToPoints(7.7) Word will not set this property automatically to the total width of your columns.
Your table has 3 columns which you can address as Tbl.Columns(1) to 3. You can set the width for each column, like Tbl.Columns(3).Width = InchesToPoints(5.1)
Similarly, you can address each row as Tbl.Rows(1) and up. Individual cells are addressed by Row and Column numbers, for example, Tbl.Cell(1, 3) which is the 3rd cell in the first row. Avoid merging cells because that will prevent VBA from being able to count them off.
The text in a cell is contained in its range, for example, Tbl.Cell(1, 3).Range.Text. You can both read and write this property. Bear in mind that Word keeps a paragraph-end mark at the end of each cell's range. When you write to a cell Word will add it for you, even if you thought of adding it yourself. But when you read a cell's text you need to remove the last character, for example,
Dim Rng As Range
Set Rng = Tbl.Cell(1, 3).Range
With Rng
.End = .End - 1
Fun = .Text
End With
Here Fun is the variable (As String) that contains the actual text part of the cell's contents.
You can address the paragraphs within a cell as part of the range, for example, Tbl.Cell(1, 3).Range.Paragraphs(1). I always avoid having more than 1 paragraph into any cell. However, you could address more paragraphs as (2) etc. You can apply all formatting available for paragraphs to each paragraph in each cell, and all the text in each paragraph can be subjected to all the formatting Word has available for text.

(Excel VBA) - Draw from cell text in a macro

I'm trying to build a small macro that allows the user to format multiple different documents at once.
I would like for the user to be able to enter into a particular cell within the document containing the macro a particular piece of text.
I then want for this piece of text to be able to be drawn upon in the macro while affecting a different document.
For instance, a code to add another column might say
Worksheets(1).Range("A1").EntireColumn.Insert
Instead of specifying the column (A), I would like it to draw on a value in the host document. For instance, the user types "G" into the particular cell, and then clicks a button to run the macro, and the macro will dynamically know to affect column G in all excel documents it targets based off of the value in the host document.
I hope this makes sense.
Any suggestions for the sort of functions I should be looking at to make this work?
"Any suggestions on the sort of functions I should be looking at?"
Here's a few...
To get the value which is entered...
If the cell will always be in the same address, say A1:
' Define a string variable and set it equal to value in A1
Dim cellText as String
cellText = ThisWorkbook.ActiveSheet.Range("A1").Value
or instead of using Range you can also use Cells which takes a row and column number.
cellText = ThisWorkbook.ActiveSheet.Cells(1, 1).Value
If the cell changes then you may need to look into the Find function to look for a label/heading next to the input cell. Then you can use it (easily with Cells) to reference the input...
Once you have this variable, you can do what you like with it.
To put this value into cell B3 in another (open) workbook named "MyWorkbook", and a sheet named "MySheet" you can do:
Application.Workbooks("MyWorkbook").Sheets("MySheet").Range("B3").Value = cellText
To insert a column at cellText, do
Application.Workbooks("MyWorkbook").Sheets("MySheet").Range(cellText & "1").EntireColumn.Insert
Notably here, the & concatonates the strings together, so if
cellText="B"
then
cellText & "1" = "B1"
Further to your comment about moving values between sheets, see my first example here, but always refer to the same workbook. If you find yourself repeatedly typing something like
ThisWorkbook.Sheets("MySheet").<other stuff>
then you can use the With shorthand.
With ThisWorkbook.Sheets("MySheet")
' Starting anything with a dot "." now assumes the with statement first
.Range("A1").Value = .Range("A2").Value
.Range("B1").Value = .Range("B2").Value
End With
Important to note is that this code has no data validation to check the cell's value before using it! Simply trying to insert a column based on a value which could be anything is sure to make the macro crash within its first real world use!

Adding text to a cell in Excel using VBA

I've been working with SQL and Excel Macros, but I don't know how to add text to a cell.
I wish to add the text "01/01/13 00:00" to cell A1. I can't just write it in the cell because the macro clears the contents of the sheet first and adds the information afterwards.
How do I do that in VBA?
Range("$A$1").Value = "'01/01/13 00:00" will do it.
Note the single quote; this will defeat automatic conversion to a number type. But is that what you really want? An alternative would be to format the cell to take a date-time value. Then drop the single quote from the string.
You could do
[A1].Value = "'O1/01/13 00:00"
if you really mean to add it as text (note the apostrophe as the first character).
The [A1].Value is VBA shorthand for Range("A1").Value.
If you want to enter a date, you could instead do (edited order with thanks to #SiddharthRout):
[A1].NumberFormat = "mm/dd/yyyy hh:mm;#"
[A1].Value = DateValue("01/01/2013 00:00")
You need to use Range and Value functions.
Range would be the cell where you want the text you want
Value would be the text that you want in that Cell
Range("A1").Value="whatever text"
You can also use the cell property.
Cells(1, 1).Value = "Hey, what's up?"
Make sure to use a . before Cells(1,1).Value as in .Cells(1,1).Value, if you are using it within With function. If you are selecting some sheet.