how to use MS word 2007 vba to check window verion - vba

I wanna check the window version on different comp thus to do different task on MS word 2007 vba. i tried this code which i applied on ms excel 2007 vba and is working, but not on MS word 2007 vba.
Dim TheOS As String
Dim WinType As String
TheOS = Application.OperatingSystem
MsgBox ("TheOS ")
On the ms word 2007 vba, it reurn a compile error:method or data member not found. what do i need?

If you want vba code that can be used all over the office products WMI is one solution.
The thing with Application.System.OperatingSystem that its not returning anything interesting.
Application.System.Version is usable. But I use the WMI to give me the correct information.
Sub test()
Dim info As System
'Well everything is windows NT today..
Debug.Print Application.System.OperatingSystem
'Short version string MajorVersion.MinorVersion
Debug.Print Application.System.Version
Dim objWMI As Object
Dim objSystems As Object
Dim objOs As Object
Set objWMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set objSystems = objWMI.ExecQuery("Select * from Win32_OperatingSystem")
For Each objOs In objSystems
Debug.Print objOs.Name 'Full name as in OS startup screen
Debug.Print objOs.Caption ' Human readable name
Debug.Print objOs.Version ' the correct windows version string
Next
Set objOs = Nothing
Set objSystems = Nothing
Set objWMI = Nothing
End Sub

Related

Run Time Error Generated when opening Microsoft Word Document from Excel VBA

Receiving a Runtime Error '13' exception when creating a word application object. I also was experiencing relatively extreme delays (on the order of 20-30 seconds) of running prior to the exception. Any idea what this could be from? I searched Stackoverflow and I haven't seen anything that was very similar.
I have never worked with an word doc from excel before so this is something new to me.
Code Below:
Public Sub GetRawData()
'Meant to translate data from a raw word file and format into excel
Dim filePath As String
Dim objWord As Application
Set objWord = CreateObject("Word.Application")
Dim objDoc As Word.Document
'File management vars
Dim oneLine As Paragraph
Dim lineText As String
filePath = "U:\Research_Dev Docs\DevFolder\Word Doc Translation In Excel For Phys\testWordDoc.docx"
'Set word doc object using standard file directory and file name
Set objDoc = objWord.Documents.Open(Filename:=filePath, Visible:=True)
For Each oneLine In objDoc.Paragraphs
'Pull in each line and eventually parse
lineText = oneLine.Range.Text
'DEBUG OUTPUT TO THE SCREEN FOR TESTING
MsgBox (lineText)
Next oneLine
End Sub

vb.net & office: Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass'

I'm developing a vb.net application and it should open and handle a excel file.
The problem is that in my pc (and the same could happen in other pc where it could be installed) I have Visio version 2013 and Office (excel, word, etc..) version 2010. Integrating excel in vb is so simple because more or less automatic, done in few steps.. but in the same time so stupid: calling interop.Excel functions, it addresses to the newest version of office intalled (2013), but I don't have excel for that version!
I searched a lot on the web about this issue, and every where I found the solution of deleting a registry key, well, it works fine, but every time I use Visio, it seems the registry key is recreated again.
My questions are:
can I select which version of excel I would like to link my application?
I can understand that fixing the version I should handle any office versions
manually.. but maybe I prefer doing this..
can I copy a dll in the application folder to be sure that the app uses that
version? I tried with Microsoft.Office.Interop.Excel.dll and Office.dll but still the issue
I don't want to follow the way of deleting the registry key programmatically, is not safe in my opinion..
I can't believe that the integration between office and .net is so stupid that is not able to use the right version of excel installed!!
;-P
Code:
Dim fileTest As String = FilePath
Dim APP As New Application
MsgBox(APP.Version)
Dim oSheet As Excel.Worksheet = Nothing
Dim workbook As Excel.Workbook = Nothing
Dim IndexFound As Integer = 0
Dim StartRow As Integer = 10
Dim DateSelected As String = ""
Dim resultOK As Boolean = False
Try
workbook = APP.Workbooks.Open(fileTest)
oSheet = workbook.Worksheets("Activities")
APP.DisplayAlerts = False
oSheet.Range("A2").Value = "test"
oSheet.Range("B3").Value = "Ciao"
Catch ex As Exception
MsgBox("Error: " + ex.Message)
If Not resultOK Then
If Not workbook Is Nothing Then
workbook.Close()
While System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook) > 0
End While
workbook = Nothing
End If
oSheet = Nothing
workbook = Nothing
APP.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(APP)
APP = Nothing
GC.Collect()
GC.WaitForPendingFinalizers()
End If
End Try
End Sub
Thanks
Andrea

Finding the LastRow from Excel Attachment via Outlook VBA

I've been searching for an answer to this particular issue but I can't seem to find one. I am trying to combine multiple Excel-based lists that I receive as e-mail attachments. Just to give a little context, this macro has been working for almost two years without error but I recently switched it from a system running Excel 2007 & Outlook 2010 to a system running Excel 2007 & Outlook 2007.
The following line is giving me an 1004: Application-defined or object-defined error:
LR = xlAtt.ActiveSheet.Range("A" & xlAtt.ActiveSheet.Rows.Count).End(xlUp).Row
in context the code is:
Private Sub ProcessAttachments(olFolder As Outlook.MAPIFolder)
Dim xlApp As Object, xlAtt As Object
Dim LR As Long
Dim olItem As Outlook.MailItem
Dim count As Integer
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = False
For count = olFolder.Items.Count To 1 Step -1
Set olItem = olFolder.Items.Item(count)
If olItem.Class = olMail And olItem.Attachments.Count > 0 Then
'Omitted a few lines here that verify if the attachment is an Excel file
'and then saves it to a folder
Set xlAtt = xlApp.Workbooks.Open("pathToFile")
xlAtt.Activate
LR = xlAtt.ActiveSheet.Range("A" & xlAtt.ActiveSheet.Rows.Count).End(xlUp).Row
'More VBA after
The above is just a snippet of the code but hopefully gives enough context.
I have tried testing each individual piece of the line giving me an error and I've been able to narrow it down to the .End(xlUp).Row portion of the line.
Any help is appreciated.
Outlook 2007 must not recognize the Excel Constants, whereas OL 2010 does.
Instead of writing xlUp write the enumeration for xlUp which is -4162.
So your code would look like this:
LR = xlAtt.ActiveSheet.Range("A" & xlAtt.ActiveSheet.Rows.Count).End(-4162).Row
To find any enumeration for any constant in Excel VBA, once inside the VBE, press F2 to open the Object Browser and type the constant into the box next to the binoculars, then click the binocular. Click on the constant in the search results and the box at the bottom will show the enumeration.
Alternatively, you could set a constant variable to the enumeration and still use xlUp in your syntax by:
Constant xlUp = -4162

Writing Data from Excel to Word

I want to use Excel to store "tag names" in column A and their associated "replacement text" in Column B. When the code runs, it needs to collect each tag, one at a time (row by row), search an entire Word document for those words, and replace them with their corresponding replacements.
I noticed the special tags in the headers and footers weren't being replaced. I turned to this article (http://word.mvps.org/faqs/customization/ReplaceAnywhere.htm) and found that working with a range of ranges (or cycling through all available Story Ranges in the document) I was able to do this.
I improved my code, as recommended in the link above and it worked, so long as my code was embedded in my "Normal" Word file, thereby using my VBA code from Word to operate on another Word document. However, the goal is to use VBA Excel to operate the replacements while reading an Excel file.
When I moved the code to Excel, I'm getting hung up on an Automation error which reads,
"Run-time error '-2147319779 (8002801d)': Automation error Library not registered.".
I've looked for answers from reviewing the Registry to using "Word.Application.12" in place of "Word.Application".
I have a Windows 7, 64-Bit machine, with Microsoft Office 2007. I have the following libraries selected:
Excel:
Visual Basic For Applications
Microsoft Excel 12.0 Object Library
OLE Automation
Microsoft Access 12.0 Object Library
Microsoft Outlook 12.0 Object Library
Microsoft Word 12.0 Object Library
Microsoft Forms 2.0 Object Library
Microsoft Office 14.0 Object Library
Word:
Visual Basic For Applications
Microsoft Word 12.0 Object Library
OLE Automation
Microsoft Office 12.0 Object Library
I have no issues with operating inside of Excel with regard to VBA. Normally, I will be passing a set of strings to this function, but for now, I have embedded the strings inside of the function, as if I am only planning on swapping one string (for any number of instances), with another predetermined string.
Function Story_Test()
Dim File As String
Dim Tag As String
Dim ReplacementString As String
Dim a As Integer
Dim WordObj As Object
Dim WordDoc As Object
Dim StoryRange As Word.Range
Dim Junk As Long
Dim BaseFile As String
'Normally, these lines would be strings which get passed in
File = "Z:\File.docx"
Tag = "{{Prepared_By}}"
ReplacementString = "Joe Somebody"
'Review currently open documents, and Set WordDoc to the correct one
'Don't worry, I already have error handling in place for the more complex code
Set WordObj = GetObject(, "Word.Application")
BaseFile = Basename(File)
For a = 1 To WordObj.Documents.Count
If WordObj.Documents(a).Name = BaseFile Then
Set WordDoc = WordObj.Documents(a)
Exit For
End If
Next a
'This is a fix provided to fix the skipped blank Header/Footer problem
Junk = WordDoc.Sections(1).Headers(1).Range.StoryType
'Okay, this is the line where we can see the error.
'When this code is run from Excel VBA, problem. From Word VBA, no problem.
'Anyone known why this is???
'***********************************************************************
For Each StoryRange In WordObj.Documents(a).StoryRanges
'***********************************************************************
Do
'All you need to know about the following function call is
' that I have a function that works to replace strings.
'It works fine provided it has valid strings and a valid StoryRange.
Call SearchAndReplaceInStory_ForVariants(StoryRange, Tag, _
ReplacementString, PreAdditive, FinalAdditive)
Set StoryRange = StoryRange.NextStoryRange
Loop Until StoryRange Is Nothing
Next StoryRange
Set WordObj = Nothing
Set WordDoc = Nothing
End Function
For Each StoryRange In WordObj.Documents(a).StoryRanges
should probably be
For Each StoryRange In WordDoc.StoryRanges
since you just assigned that in the loop above.
For now, I will have to conclude, as I don't have the possibility of testing the contrary, that there is a difference between using Microsoft Office 12 Object Library in one VBA environment, and Microsoft Office 14 Object Library in another. I don't have the means/authorizations to change either, so I must conclude, for now that is, that the difference between the two is the culprit. So, if I was to go forward and expect different results, I would assume Microsoft Office 12 Object Library to be the correct library, where 14 has a few differences that I am not aware of.
Thank you to all who provided input. If you have any other suggestions, we can discuss and forward. Thanks!
This is to update a bunch of links spread over body & Headers footers.
I didn't write this only from memory made a bunch of fixes, inclusions and tweaks.
It shows you how to cover all the different sections and can easily be modified to work within your parameters.
Please post your final code once done.
Public Sub UpdateAllFields()
Dim doc As Document
Dim wnd As Window
Dim lngMain As Long
Dim lngSplit As Long
Dim lngActPane As Long
Dim rngStory As Range
Dim TOC As TableOfContents
Dim TOA As TableOfAuthorities
Dim TOF As TableOfFigures
Dim shp As Shape
Dim sctn As Section
Dim Hdr As HeaderFooter
Dim Ftr As HeaderFooter
' Set Objects
Set doc = ActiveDocument
Set wnd = ActiveDocument.ActiveWindow
' get Active Pane Number
lngActPane = wnd.ActivePane.Index
' Hold View Type of Main pane
lngMain = wnd.Panes(1).View.Type
' Hold SplitSpecial
lngSplit = wnd.View.SplitSpecial
' Get Rid of any split
wnd.View.SplitSpecial = wdPaneNone
' Set View to Normal
wnd.View.Type = wdNormalView
' Loop through each story in doc to update
For Each rngStory In doc.StoryRanges
If rngStory.StoryType = wdCommentsStory Then
Application.DisplayAlerts = wdAlertsNone
' Update fields
rngStory.Fields.Update
Application.DisplayAlerts = wdAlertsAll
Else
' Update fields
rngStory.Fields.Update
End If
Next
'Loop through text boxes and update
For Each shp In doc.Shapes
With shp.TextFrame
If .HasText Then
shp.TextFrame.TextRange.Fields.Update
End If
End With
Next
' Loop through TOC and update
For Each TOC In doc.TablesOfContents
TOC.Update
Next
' Loop through TOA and update
For Each TOA In doc.TablesOfAuthorities
TOA.Update
Next
' Loop through TOF and update
For Each TOF In doc.TablesOfFigures
TOF.Update
Next
For Each sctn In doc.Sections
For Each Hdr In sctn.Headers
Hdr.Range.Fields.Update
For Each shp In Hdr.Shapes
With shp.TextFrame
If .HasText Then
shp.TextFrame.TextRange.Fields.Update
End If
End With
Next shp
Next Hdr
For Each Ftr In sctn.Footers
Ftr.Range.Fields.Update
For Each shp In Ftr.Shapes
With shp.TextFrame
If .HasText Then
shp.TextFrame.TextRange.Fields.Update
End If
End With
Next shp
Next Ftr
Next sctn
' Return Split to original state
wnd.View.SplitSpecial = lngSplit
' Return main pane to original state
wnd.Panes(1).View.Type = lngMain
' Active proper pane
wnd.Panes(lngActPane).Activate
' Close and release all pointers
Set wnd = Nothing
Set doc = Nothing
End Sub

Using excel as inputfile in vba (scripting - non MS OFFICE)

I'm developing a script in VBA (inside a workspace, not MS office program) that needs to use a small excel file as input. I want to use the data in the excel file and load it into a 2D array so that I can make decisions within my script based on this data.
I've tried to google this problem but generally I find problems within excel, but I haven't had any luck finding anything for vba scripting outside MS office.
Can I just use a .Xlsx as inputfile?
How do I put this data into a 2d array? My file only has 11 rows & 2 columns.
Thank you for your time.
This is confusing. VBA = MS Office VBA, as far as I know. Do you mean VB.NET? VBS? Anyway, to extract data from an xlsx file without opening it in Excel, you either need to unzip it and dig through the XML files inside, or use Office Open XML SDK or any other package like that.
Open XML SDK
Office Open XML fileformat
I think this will also work for Visual Basic [for Applications]; I tried it in Excel VBA and Word VBA:
In VBA Development Environment, select Tools, References. In the list that now appears, check the Object Model you need. In your case you will want to check the Microsoft Excel 12.0 Object Library.
You now have access to the complete Excel Object Model in your application and can open and manipulate an Excel spreadsheet file as you need.
The following code in VB for Word opens an Excel Spreadsheet and gets the value of the first cell:
Sub ExcelTestInWord()
Dim oExcel As Object
Dim wb As Object
Dim v
'Declare a variable as a FileDialog object.
Dim fd As FileDialog
Dim vrtSelectedItem As Variant
Set oExcel = CreateObject("Excel.Application")
'Create a FileDialog object as a File Picker dialog box.
Set fd = Application.FileDialog(msoFileDialogFilePicker)
If (fd.Show = -1) Then
For Each vrtSelectedItem In fd.SelectedItems
Set wb = oExcel.Workbooks.Open(vrtSelectedItem)
v = wb.Sheets(1).Cells(1).Value
wb.Close
Next vrtSelectedItem
End If
End Sub
Consider the VBScript code below as an example, save it as .vbs file to launch:
Option Explicit
Dim strSourceFilePath, strSourceSheetName, strSourceRange, arrData, strResult, i, j
' set initial data
strSourceFilePath = "C:\Test\data.xlsx"
strSourceSheetName = "input"
strSourceRange = "A1:B11"
' get 2-dimensional array from Excel sheet
With CreateObject("Excel.Application")
.Visible = False
.DisplayAlerts = False
With .Workbooks.Open(strSourceFilePath)
arrData = .Sheets(strSourceSheetName).Range(strSourceRange).Value
.Close
End With
.Quit
End With
' array output for debug purposes
strResult = ""
For j = 1 To UBound(arrData, 1)
For i = 1 To UBound(arrData, 2)
strResult = strResult & arrData(j, i) & ";" & vbTab
Next
strResult = strResult & vbCrLf
Next
WScript.Echo strResult