Save Word document as a filename generated from tabled info contained within the document - vba

I am looking to enable Word to save with a file name using data contained within the document.
At the top of the document (an airline release letter), there is a table containing 2 columns with 3 rows containing alpha in one column and alpha-numeric data in column 2.
Column 1,
Cell 1: AETC; Cell 2: MAWB; Cell 3: HAWB
Column 2,
Cell 1: 80123; Cell 2, 0161234567; Cell 3: 00112345678
Basically, the first column will be the static labels for the variable data to be entered into column 2.
From all this, I want to generate a save-as file name: AETC80123_MAWB0161234567_HAWB00112345678_ReleaseLetter.doc
I've barely scratched the surface of VBA as I am more an operations supervisor than a techie so I'm not certain if this is even possible.
Any help/direction/copy-paste coding (if it's super easy and of little trouble) would be awesome!
Thanks!

I am not going to work it all out in detail for, nor is this tested at all (just written out of my head), but this should give a hint how you read cell content in a Word document:
' Set tbl to first table in document
Dim tbl As Table
Set tbl = ActiveDocument.Tables(0)
Dim r As Integer
Dim c As Integer
Dim val As String
Dim filename As String
filename = ""
For r = 1 To tbl.Rows.Count
For c = 1 To tbl.Columns.Count
' Get text in cell
val = tbl.Cell(r, c).Range.Text
' and append to string or whatever
filename = filename & val & "_"
Next c
Next r
Finally, save your document using
ActiveDocument.SaveAs FileName:=filename
Check this microsoft site for more information about SaveAs parameters.

Related

How to use a word table as mailmerge datasource

I have a word document containing a table I need to use as mailmerge datasouce.
I've reached my goal by copying data of the word table to excel and using the sheet as datasource.
Now my question is: is there a way to use the word table as datasource (I mean create a datasource using the data in the word table) without calling excel?
I'm asking this because I need to use a word-vba macro and I'm trying to avoid opening an excel instance.
edit
I'll try to clarify what I'm looking for with the following pseudocode (I added a "What for this?" in wrong code lines):
Dim mDoc As Document
Dim mTbl As Table
Set mDoc = ActiveDocument
Set mTbl = mDoc.Tables(1)
Dim mDS As MailMerge.DataSource 'What for this?
For C = 1 To mTbl.Columns.Count
'Add Fields
Dim FieldName As String
FieldName = mTbl.Cell(1, C).Range.Text
mDS.Fields.Add (FieldName) 'What for this?
'Add Values
For R = 2 To mTbl.Rows.Count
mDS.Fields(FieldName)(R) = mTbl.Cell(R, C).Range.Text 'What for this?
Next R
Next C
In Word, start with a blank document, then add one table. Enter the category in the top row (i.e. First Name, Last Name, etc). Then add the data in the rows below. Then you should be able to use a statement like this to connect:
ActiveDocument.MailMerge.OpenDataSource Name:="Y:\Test\Word\MailmergeSource.docx", LinkToSource:=True, SubType:=wdMergeSubTypeOther

Excel VBA extract substring based on InStr and paste into worksheet2 loop for all cells in column

Microsoft Excel VBA
I have a list of strings containing shop ID codes & address combined in column Y, and I want to go down this list, extract just the ID code, and paste this into a second spreadsheet in column C.
I am struggling with how to use a For statement to loop this for each cell in the columns, as I want the statement to find the info from a cell in Activesheet column Y, then paste the substring into Sheet Part 1 Column C, and then loop to the next cell in the range for both sheets.
My insufficient code:
set up a for loop for the Y column in ActiveSheet, where the shop ID info is stored
For Each cell In ActiveSheet.Range("Y:Y")
create a location variable to store the instr value, should change each loop, not sure if this is the way to do it however
Dim location As Integer
create an object that stores where the ID code finishes in my string
location = InStr(1, ActiveSheets.Range("Y:Y"), " ")-1
using the left function with the location object, tell excel I want to copy the shop ID and paste it into column C in the Part 1 Sheet.
Left(xCell, location).Copy Sheets("Part 1").Range("C:C")
Next
Full Code without annotations:
For Each cell In ActiveSheet.Range("Y:Y")
Dim location As Integer
location = InStr(1, ActiveSheets.Range("Y:Y"), " ")-1
Left(xCell, location).Copy Sheets("Part 1").Range("C:C")
Next
Thanks for any advice
Dim Location as long
Dim c as range
For each c in range("Y:Y")
Location = instr(" ",trim(c.text))
if location >0 then
sheets("Part 1").range("C" & c.row).value = left(c,location)
end if
next c
This assumes that you want them to appear in column C in the same row as they are in in column Y
Edit to fix my error and to add a trim - I suspect you have a leading space in column Y?

Best way to populate an excel string column for fastest subsequent vba search (can I use metadata, etc?)

In a column with hundreds or even 1-2 thousand strings of approximately 40 characters, with one string per cell and many repeating entries, what is the best way to populate the column to conduct the fastest possible search later? The search should return a row number so that the corresponding row can be deleted.
Is there some way to append metadata or label to a cell/row for faster search? Is there some other mechanism that can identify cells that will make searching easier?
I'm new to VBA, and I want to set out on the best path before I get too far into the project and have to search through thousands of strings.
edit: Someone requested an example cell: The cells will have email addresses in them. I can control the email addresses on the server, so they will roughly be 40 characters long each. They will contain alphanumeric characters only.
Example of a fast way to implement a dictionary lookup
Data is on Sheet1, and starts in column A
The strings are in column B
Option Explicit
Public Sub SearchStrings()
Dim ur As Variant, r As Long, d As Object
Const COL_ID = 2
Set d = CreateObject("Scripting.Dictionary") 'or Reference to Microsof Scripting Runtime
d.CompareMode = TextCompare 'Case insensitive, or "BinaryCompare" otherwise
ur = Sheet1.UsedRange.Columns(COL_ID) 'read strings from column COL_ID into array
For r = LBound(ur) To UBound(ur) 'populate dictionary; Key = string (unique)
If Not IsError(ur(r, 1)) Then d(CStr(ur(r, 1))) = r 'Item = row id
Next
Debug.Print d.Keys()(3) 'prints the string in row 3
Debug.Print d.Items()(3) 'prints the row number of the 3rd string
End Sub
If you want to store string duplicates use this:
If Not IsError(ur(r, 1)) Then d(COL_ID & "-" & r) = CStr(ur(r, 1))
which is Key = Column ID & "-" & row ID (2-5), and Item = String itself

Excel Rows (1st column) as .php files + Excel Row 1 (2nd column to infinty) as data of all files

I found relevent things but not the exact match and I don't know how fix them.
I have an excel file with only 1 row(with many columns) and 1 column (with many rows).
Now I would like to use vba and create files from all the rows of 1st column and , put the same data (i.e. cloumn b to infinty of 1st row) inside all the files.
Just an example:
excel file:
a 2 3 4
b
c
files would be:
a.php, b.php, c.php
with same data inside them:
2 3 4
Thanks in advance
While the rationale for doing this to generate web content eludes me, this is trivial to do. Just loop through the 1st row to get the data, then loop through the first column to get the filenames and output copies:
Const path = "C:\YourDestinationDirectory\"
Public Sub DumpPHP()
Dim sheet As Worksheet
Dim data As String
Dim index As Long
Set sheet = ActiveSheet
For index = 2 To sheet.UsedRange.Columns.Count
data = data & sheet.Cells(1, index)
Next index
Dim handle As Integer
For index = 2 To sheet.UsedRange.Rows.Count
handle = FreeFile
Open path & sheet.Cells(index, 1) & ".php" For Output As #handle
Print #handle, data
Close #handle
Next index
End Sub

Excel pulling data from certain cells

I have a file that I only want to extract cells B9, B19, B29, etc etc etc in a pattern throughout the entire file. I would preferably like it to be extracted to a different excel file or someway so that I can do stuff with only those cells in another excel worksheet.
Potentially, I may have several excel files that I may need to do this sort of thing so if there were a way where I had the same format throughout a lot of files that I could always extract cells B9, B19, B29 that would be great. any help appreciated
I looking for syntax if possible
EDIT
Was thinking if I could somehow make an excel IF statement saying if Row has a 9 in it and the row is B then print it somewhere but I want it printed in a column
EDIT 2
I just want column B not A like I mentioned before.
B9, B19,B29,B39 through the whole file
Just in case you want to do it with code:
Sub Test()
'Assumes Sheet1 has your values and Sheet2 will be the data extracted from every row ending in 9
Dim iCounter As Long
Dim newSheetRow As Long
Dim aValue As String
Dim bValue As String
newSheetRow = 1
'Start and nine and increment by 10 till you reach end of sheet
For iCounter = 9 To Sheet1.Rows.Count - 1 Step 10 'NOTE: You may not want to do it by RowCount, but just showing you could
aValue = Sheet1.Range("A" & iCounter)
bValue = Sheet1.Range("B" & iCounter)
Sheet2.Range("A" & newSheetRow).Value = "We were on row: " & iCounter
Sheet2.Range("B" & newSheetRow).Value = aValue
Sheet2.Range("C" & newSheetRow).Value = bValue
newSheetRow = newSheetRow + 1
Next iCounter
MsgBox "Done"
End Sub
You could use the INDIRECT function. It takes a cell reference as a text string and returns the value in that cell. So instead of using
=data!a9
to get the value in sheet "data" in cell a9, you use
=indirect("data!a9")
You can also use r1c1 notation, like this:
=indirect("data!r9c1",false)
From there you can use the ROW and COLUMN functions to go in steps of 10:
=INDIRECT("data!r"&-1+10*ROW()&"c"&COLUMN(),FALSE)
If you put this formula in A1 of your output sheet and then copy and paste it down and across, it will give you the values in data!A9, data!A19, data!A29,... in cells A1, A2, A3... Depending on how you want your output arranged, you might have to modify the cell reference string.
Depending on how often you want to do this depends on how you need to do it, if it's a one of them some simple excel commands might help.
e.g.
In Cell C1 put the following:
=MOD(ROW(),10)
then replicate this down to the bottom of your data. the command will return the numbers 1 through to 0. You can then filter the data on column C where value is 9 then select the visible rows and copy the data to a new sheet.
ROW() ' this returns the ROW number of cell the command is in.
MOD(number, divisor) ' this basically divides one number by the other and returns the remainder. so row 9 / 10 = 0 remainder of 9, row 19 / 10 = 1 remainder of 9.
Hope this helps.