Inserting information from a cell into code - excel

I have been working on a spreadsheet where I want a VBA code to open a document, now this document could be either a word or excel document, but I want the code to use the information from a cell.
Function FnPrint()
Dim objWord
Dim objDoc
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open("Y:\Master Documents\Sheet & Cut\W19-316 Allergen cleandown S&C line.docx")
objWord.Visible = True
objDoc.PrintOut
objWord.Quit
End Function
That is the code that I have, Now where it says "Y:\Master Documents\Sheet & Cut\W19-316 Allergen cleandown S&C line.docx", I want that to actually change depending on a certain cell, which you can see in the above image. This is because that cell changes depending on the variables entered in the other boxes.
Any Ideas?

..to open a document, now this document could be either a word or excel document
Logic:
Check the file extension of the file path in the cell and then decide whether you want to open Excel or Word.
Code (Untested):
Option Explicit
Sub Sample()
Dim rngDocInfo As Range
Dim objApp As Object, objDoc As Object
Dim myPath As String
'~~> Change this to relevant sheet and cell which has the path
Set rngDocInfo = Sheet1.Range("O18")
myPath = UCase(rngDocInfo.Value2)
If Len(Dir(myPath)) = 0 Then
MsgBox "Invalid filename. File does not exist"
Exit Sub
End If
'~~> Get file extension and check if it is an Excel document
If Right(myPath, Len(myPath) - InStrRev(myPath, ".")) Like "XLS*" Then
Set objApp = CreateObject("Excel.Application")
Set objDoc = objApp.Workbooks.Open(rngDocInfo.Value2)
objApp.Visible = True
'
' Rest of the code
'
'~~> Get file extension and check if it is a Word document
ElseIf Right(myPath, Len(myPath) - InStrRev(myPath, ".")) Like "DOC*" Then
Set objApp = CreateObject("Word.Application")
Set objDoc = objApp.Documents.Open(rngDocInfo.Value2)
objApp.Visible = True
'
' Rest of the code
'
Else
MsgBox "Unknown Document type"
End If
End Sub
Note: I am not handling Text/Csv Files in the above code. If you can have those file types then amend the above code accordingly.

Related

How to copy and paste pictures from Excel to Word

I am producing a report which needs to be run daily. I have some pictures in Excel and I want to copy them and paste them into Word. I need them in a certain location. All this needs to be done in VBA.
My proposed way of doing this is by creating template pictures in Word and giving them a name (which can be seen in Home > Select > Selection Panel). I assume that I can then copy the pictures from Excel and paste them over the template pictures (i.e. replacing the template pictures) - I believe this type of technique is possible with Excel-Powerpoint.
(1) If I can execute this, will the pictures from Excel go to the right location in Word and be of the same dimensions as the template pictures?
(2) How do I select the existing named template pictures?
Here is my code so far but at the end, I am missing the ability to select the existing NAMED template pictures...
Dim wd As Object
Dim ObjDoc As Object
Dim FilePath As String
Dim FileName As String
FilePath = "OMITTED FOR PRIVACY REASONS"
FileName = "OMITTED FOR PRIVACY REASONS"
On Error Resume Next
Set wd = GetObject(, "Word.Application")
If wd Is Nothing Then
Set wd = CreateObject("Word.Application")
Set ObjDoc = wd.Documents.Open(FilePath & "\" & FileName)
Else
On Error GoTo notOpen
Set ObjDoc = wd.Documents(FileName)
GoTo OpenAlready
notOpen:
Set ObjDoc = wd.Documents.Open(FilePath & "\" & FileName)
End If
OpenAlready:
On Error GoTo 0
wd.Visible = True
ObjDoc.
Thank you so much for your time and effort!

vbs find file in directory and print with popout window

I have script that printing specific file, but it's getting hard to make over 150 .vbs files for each document to be printed,
is there any way to have pop-out window where i can type file name, then script find it in folder and print it with 20 copies.
I have PDF, WORD and Excel files
this is what i have now for them
Dim AppExcel
Set AppExcel = CreateObject("Excel.application")
AppExcel.Workbooks.Open"directory\filename.xlsx"
AppExcel.Visible = True
AppExcel.ActiveWindow.SelectedSheets.PrintOut,,20
Appexcel.Quit
Set appExcel = Nothing
filename = "\\MCSERVER01\Data\Forms\Vehicle inspection forms\daily vehicle inspection form.pdf"
Set sh = CreateObject("WScript.Shell")
sh.Run "sumatrapdf.exe -print-to-default """ & filename & """", 0, True
Dim AppWord
Set AppWord = CreateObject("Word.application")
AppWord.Documents.Open"\\MCSERVER01\Data\Forms\DODD\SMALL CAR DRIVERS\Akira Litman.docx"
AppWord.Visible = True
AppWord.ActiveDocument.PrintOut
AppWord.Quit
Set appWord = Nothing
Perhaps you can make use of an input box
Dim fileToPrint As String
fileToPrint = InputBox("Enter file name to print")
I got some help from my old friend, but now i can't get another part working
set fso = CreateObject("Scripting.FileSystemObject")
call main
sub main
InputName = InputBox("ENTER YOUR NAME")
if instr(InputName, ".") = 0 then
msgbox("DON'T NEED THIS AT ALL!!!!!")
exit sub
end if
'msgbox(mid(InputName, instr(InputName, ".")+1))
select case mid(InputName, instr(InputName, ".")+1)
case "xlsx"
call printExcel(InputName)
end select
end sub
sub printExcel(fileName)
Dim AppExcel, path
Set AppExcel = CreateObject("Excel.application")
path = "\MCSERVER01\Data\Forms\Access2Care\WHEELCHAIR DRIVERS\"
if fso.FileExists(path & fileName) then
AppExcel.Workbooks.Open path & fileName
AppExcel.Visible = false
AppExcel.ActiveWindow.SelectedSheets.PrintOut,,20
Appexcel.Quit
Set appExcel = Nothing
else
X=MsgBox ("Wrong File Name Or File Doesn't Exist" ,0+16, "Please Re-Enter Your Full Name")
end if
end sub
so the issue i have now is that i have to type in file extension to make it work otherwise im getting msgbox with "don't need this"
how i can get rid of that msg and just have default extension as xlsx xsl

VBS Save File From Link

I wonder whether someone can help me please.
I wanting to use this solution in a script I'm trying to put together, but I'm a little unsure about how to make a change which needs to be made.
You'll see in the solution that the file type which is opened is a Excel and indeed it's saved as such. But I the files I'd like to open and save are a mixture of .docx and .dat (Used by Dragon software) files.
Could someone possible tell me please is there a way by which I can amend the code so it opens and saves the files in file types other than Excel workbooks.
The reason behind this question because I'm currently using a script which creates a list of files in a Excel spreadsheet from a given folder. For each file that is retrieved there is a hyperlink, which I'd like to add fucntionality to which enables the user to copy the file and save it to a location of their choice.
To help this is the code which I use to create the list of files.
Public Sub ListFilesInFolder(SourceFolder As Scripting.folder, IncludeSubfolders As Boolean)
Dim LastRow As Long
Dim fName As String
On Error Resume Next
For Each FileItem In SourceFolder.Files
' display file properties
Cells(iRow, 3).Formula = iRow - 12
Cells(iRow, 4).Formula = FileItem.Name
Cells(iRow, 5).Formula = FileItem.Path
Cells(iRow, 6).Select
Selection.Hyperlinks.Add Anchor:=Selection, Address:= _
FileItem.Path, TextToDisplay:="Click Here to Open"
iRow = iRow + 1 ' next row number
With ActiveSheet
LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
LastRow = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
End With
For Each Cell In Range("C13:F" & LastRow) ''change range accordingly
If Cell.Row Mod 2 = 1 Then ''highlights row 2,4,6 etc|= 0 highlights 1,3,5
Cell.Interior.Color = RGB(232, 232, 232) ''color to preference
Else
Cell.Interior.Color = RGB(141, 180, 226) 'color to preference or remove
End If
Next Cell
Next FileItem
If IncludeSubfolders Then
For Each SubFolder In SourceFolder.SubFolders
ListFilesInFolder SubFolder, True
Next SubFolder
End If
Set FileItem = Nothing
Set SourceFolder = Nothing
Set FSO = Nothing
End Sub
Many thanks and kind regards
Chris
Miguel provided a fantastic solution which on initial testing appeared to work 100%. But as you will see from the comments at the end of the post there were some issues when the user cancelled the operation, so I made another post at this link where the problems were ironed out. Many thanks and kind regards. Chris
The code below shows how to retrieve the extension of a file, define an array with “allowed” extensions, and match the extension of the file to the array.
This is the outline for file manipulation, you'll just need to tailor it to you needs
Dim MinExtensionX
Dim Arr() As Variant
Dim lngLoc As Variant
'Retrieve extension of file
MinExtensionX = Mid(MyFile.Name, InStrRev(MyFile.Name, ".") + 1)
Arr = Array("xls", "xlsx", "docx", "dat") 'define which extensions you want to allow
On Error Resume Next
lngLoc = Application.WorksheetFunction.Match(MinExtensionX, Arr(), 0)
If Not IsEmpty(lngLoc) Then '
'check which kind of extension you are working with and create proper obj manipulation
If MinExtensionX = "docx" then
Set wApp = CreateObject("Word.Application")
wApp.DisplayAlerts = False
Set wDoc = wApp.Documents.Open (Filename:="C:\Documents\SomeWordTemplate.docx", ReadOnly:=True)
'DO STUFF if it's an authorized file. Then Save file.
With wDoc
.ActiveDocument.SaveAs Filename:="C:\Documents\NewWordDocumentFromTemplate.docx"
End With
wApp.DisplayAlerts = True
End if
End If
For files .Dat its a bit more complex, specially if you need to open/process data from the file, but this might help you out.
Edit:
2: Comments added
Hi IRHM,
I think you want something like this:
'Worksheet_FollowHyperlink' is an on click event that occurs every time you click on an Hyperlink within a Worksheet, You can find more here
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
'disable events so the user doesn't see the codes selection
Application.EnableEvents = False
Dim FSO
Dim sFile As String
Dim sDFolder As String
Dim thiswb As Workbook ', wb As Workbook
'Define workbooks so we don't lose scope while selecting sFile(thisworkbook = workbook were the code is located).
Set thiswb = thisworkbook
'Set wb = ActiveWorkbook ' This line was commented out because we no longer need to cope with 2 excel workbooks open at the same time.
'Target.Range.Value is the selection of the Hyperlink Path. Due to the address of the Hyperlink being "" we just assign the value to a
'temporary variable which is not used so the Click on event is still triggers
temp = Target.Range.Value
'Activate the wb, and attribute the File.Path located 1 column left of the Hyperlink/ActiveCell
thiswb.Activate
sFile = Cells(ActiveCell.Row, ActiveCell.Column - 1).Value
'Declare a variable as a FileDialog Object
Dim fldr As FileDialog
'Create a FileDialog object as a File Picker dialog box.
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
'Allow only single selection on Folders
fldr.AllowMultiSelect = False
'Show Folder picker dialog box to user and wait for user action
fldr.Show
'add the end slash of the path selected in the dialog box for the copy operation
sDFolder = fldr.SelectedItems(1) & "\"
'FSO System object to copy the file
Set FSO = CreateObject("Scripting.FileSystemObject")
' Copy File from (source = sFile), destination , (Overwrite True = replace file with the same name)
FSO.CopyFile (sFile), sDFolder, True
' check if there's multiple excel workbooks open and close workbook that is not needed
' section commented out because the Hyperlinks no longer Open the selected file
' If Not thiswb.Name = wb.Name Then
' wb.Close
' End If
Application.EnableEvents = True
End Sub
The above code Triggers when you click the Hyperlink and it promps a folder selection window.
You just need to paste the code into the Worksheet code. And you should be good to go.

CheckOut (Sharepoint) Word Document from within Excel VBA

Good Morning All,
I have fought with this for a few days now, and have not yet found a suitable solution, so I hope somebody can put me out of my misery!
From within an excel document, I have 3 buttons to check out and open 3 documents from a Microsoft Sharepoint Server. 2 files are Excel workbooks, and one is a Word document.
The excel files work absolutely fine, but the Word document always returns 'False' when the .CanCheckOut statement is reached, even though I can manually check it out on MOSS, have the correct permissions etc. I have added the Microsoft Word 11.0 Object Library reference in my Excel VBA.
Here is my code for the excel ones:
Sub CheckOutXL(FullPath As String)
Dim xlApp As Object
Dim wb As Workbook
Dim xlFile As String
xlFile = FullPath
Set xlApp = CreateObject("Excel.Application")
'Determine if workbook can be checked out.
If Workbooks.CanCheckOut(xlFile) = True Then
'Check out file
Workbooks.CheckOut xlFile
'Open File
Set xlApp = New Excel.Application
xlApp.Visible = True
Set wb = xlApp.Workbooks.Open(xlFile, , False)
'Otherwise offer the option to open read-only
Else
If (MsgBox("You are unable to check out this document at this time, would you like to open it read-only?", vbYesNo) = vbYes) Then
Set xlApp = New Excel.Application
xlApp.Visible = True
Set wb = xlApp.Workbooks.Open(xlFile, , False)
End If
End If
and for the Word one:
Sub CheckOutDoc(FullPath As String)
If Documents(docFile).CanCheckOut = True Then 'This is the one that returns FALSE
Documents.CheckOut docFile
' Set objWord = CreateObject("Word.Application") 'The commented out section was
' objWord.Visible = True 'a second way I tried to open
' objWord.Documents.Open docFile 'the file.
Documents.Open Filename:=docFile
Else
If (MsgBox("You are unable to check out this document at this time, would you like to open it read-only?", vbYesNo) = vbYes) Then
Documents.Open Filename:=docFile
End If
End If
End Sub
These are both called using a simple line for each button as such:
Private Sub btnTrend_Click()
Call CheckOutXL("FullPathOfTheFileInHere.xls")
End Sub
Any help massively appreciated!! Thanks
We are having the same issue. Can you try this:
If CBool(Documents(docFile).CanCheckOut) = True Then

Updatelinks in Powerpoint from identical workbook in different directory (through vba?)

I am working on linking charts in powerpoint (ppt) slides to charts in Excel (xls) workbooks. This works fine without vba code, as I just use paste special to create a link. The problem is however when I change the directoy of the ppt as well as the xls, as the ppt will still try to update the data from the xls in the old directory. My goal however would be to share these files, so everyone can just update their ppt with their xls.
So, to put it shortly, I want to update the ppt, but choose a different workbook (with a different directory). This workbook will be identical to the old one in terms of structure, just with diffeerent data.
I know there is the method updatelinks, but there doesn't seem to be any way to choose a different directory with this method. Does anyone have any tips?
So, to put it shortly, I want to update the ppt, but choose a different workbook (with a different directory). This workbook will be identical to the old one in terms of structure, just with different data.
TRIED AND TESTED with MS-OFFICE 2010
I have commented the code so that you will not have a problem understanding it. If you still do then feel free to ask.
Option Explicit
Sub UpDateLinks()
'~~> Powerpoint Variables/Objects
Dim ofd As FileDialog
Dim initDir As String
Dim OldSourcePath As String, NewSourcePath As String
'~~> Excel Objects
Dim oXLApp As Object, oXLWb As Object
'~~> Other Variables
Dim sPath As String, OldPath As String, sFullFileOld As String
Dim oldFileName As String, newFileName As String
'Set the initial directory path of File Dialog
initDir = "C:\"
'~~> Get the SourceFullName of the chart. It will be something like
' C:\MyFile.xlsx!Sheet1![MyFile.xlsx]Sheet1 Chart 1
OldSourcePath = ActivePresentation.Slides(1).Shapes(1).LinkFormat.SourceFullName
Set ofd = Application.FileDialog(msoFileDialogFilePicker)
With ofd
.InitialFileName = initDir
.AllowMultiSelect = False
If .Show = -1 Then
'~~> Get the path of the newly selected workbook. It will be something like
' C:\Book2.xlsx
sPath = .SelectedItems(1)
'~~> Launch Excel
Set oXLApp = CreateObject("Excel.Application")
oXLApp.Visible = True
'~~> Open the Excel File. Required to update the chart's source
Set oXLWb = oXLApp.Workbooks.Open(sPath)
'~~> Get the path "C:\MyFile.xlsx" from
'~~> say "C:\MyFile.xlsx!Sheet1![MyFile.xlsx]Sheet1 Chart 1"
OldPath = Split(OldSourcePath, "!")(0)
'~~> Get just the filename "MyFile.xlsx"
oldFileName = GetFilenameFromPath(OldPath)
'~~> Get just the filename "Book2.xlsx" from the newly
'~~> Selected file
newFileName = GetFilenameFromPath(.SelectedItems(1))
'~~> Replace old file with the new file
NewSourcePath = Replace(OldSourcePath, oldFileName, newFileName)
'Debug.Print NewSourcePath
'~~> Change the source and update
ActivePresentation.Slides(1).Shapes(1).LinkFormat.SourceFullName = NewSourcePath
ActivePresentation.Slides(1).Shapes(1).LinkFormat.Update
DoEvents
'~~> Close Excel and clean up
oXLWb.Close (False)
Set oXLWb = Nothing
oXLApp.Quit
Set oXLApp = Nothing
End If
End With
Set ofd = Nothing
End Sub
Public Function GetFilenameFromPath(ByVal strPath As String) As String
If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then
GetFilenameFromPath = _
GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
End If
End Function

Resources