I would like to insert an Excel document into an Excel worksheet. I can do this manually by the following steps;
Insert / Text / Object / Create From File (tick Display as Icon) / Browse.
I then select the file and insert the document.
I would like to do this via a macro. (The recorder won't let you record it.)
This code I have basically is Insert / Text / Object
Sub ShowInsertObj()
Application.Dialogs(xlDialogInsertObject).Show
End Sub
I would like to add code so that a directory (lets say C:\temp) will automatically be selected and display as icon will be ticked - instead of applying the above steps.
Not sure if exactly what you wanted is possible, but you might want to use GetOpenFilename and .OLEObjects instead of xlDialogInsertObject.
Sub ShowInsertObj()
Dim Fl As Variant
Dim Filename As String
'Set your drive
ChDrive "C:"
ChDir "C:\temp"
'Grab your file filtered for Excel files
Fl = Application.GetOpenFilename(FileFilter:="Excel Workbooks (*.xls; *.xlsm),*.xls;*.xslm")
If Fl = False Then Exit Sub
' To display the filename only and not the path
Filename = Mid$(F1, InStrRev(F1, "\") + 1, Len(F1))
'Add as object to the worksheet
Sheet1.OLEObjects.Add Filename:=Filename, Link:=True, DisplayAsIcon:=True, IconFileName:="EXCEL.EXE", IconIndex:=0, IconLabel:=Filename
End Sub
Note: I used FileFilter since you said you wanted to insert an Excel file
Related
I would like to open my Word file (to make the changes then save it under different name).
I can't open my file.
My first code:
Sub RamsOpen2()
Dim Doc
Dim DocPath
Dim DocObj
Dim VarResult
DocPath = "C:\Users\mariuszk\Desktop\cf10\RAMS.docx"
Set DocObj = CreateObject("word.Application")
Doc = DocObj.Documents.Open(DocPath)
DocObj.Visible = True
With Doc.ActiveDocument
Set myRange = .Content
With myRange.Find
.Execute FindText:="FindText", ReplaceWith:="ReplaceText", Replace:=2
End With
End With
VarResult = Doc.GetSaveAsFilename( _
FileFilter:="DP Document (*.doc), *.doc, DP Document (*.docx), *.docx", Title:="Save DP",
initialvalue:="InitialDocument")
End Sub
which comes from here:
EXCEL VBA to Open Word, Edit and Saveas in the specified location.
This is roughly what I want to do with my Word file, however question is on the first step.
I have read here, that it is a common problem. VBA Excel - Unable to open existing Word Document file
I found a closer answer to my situation here: Excel macro - open specific word file
Following the advice from this query I mounted the following code:
Sub RamsOpen3()
Dim appWD As Word.Application
Set appWD = New Word.Application
Dim docWD As Word.Document
Set docWD = appWD.Documents.Open("C:\Users\mariuszk\Desktop\cf10\RAMS.docx")
appWD.Visible = True
'
' Data is selected and copied into "Design"
'
'Copy all data from Design
Sheets("Frontsheet").Select
Range("D18").Copy
' Tell Word to create a new document
appWD.Selection.Paste
' Save the new document with a sequential file name
Sheets("Sheet1").Select
appWD.ActiveDocument.SaveAs filename:=ThisWorkbook.path & "/" & "TEST" & Range("C8").Text
' Close this new word document
appWD.ActiveDocument.Close
' Close the Word application
appWD.Quit
End Sub
but the problem is the same.
Another answer is here: Excel VBA to Open Multiple Word files in a loop
but I don't want to open all Word documents in the folder.
This simple solution: VBA to open Excel or/and Word Files
also brings the same error.
As Fink pointed out in the comments your file icon looks like your file is a docm file. Since icons are chosen by file extensions there is only one solution: Check if you have file extensions turned invisible in Explorer (https://fileinfo.com/help/windows_10_show_file_extensions).
Your file is obviously called RAMS.docx.docm but you cannot see the file extension .docm.
Checkout if the following works
Set docWD = appWD.Documents.Open("C:\Users\mariuszk\Desktop\cf10\RAMS.docx.docm")
or turn on your file extension view and rename the file.
EDIT:
I started a new workbook and tore down the original code to test in a fresh environment. None of the OLEObjects.add methods seem to work even in this sanitized environment. I'm beginning to think that this method and parameters fundamentally do something other than what I think they do based on their documentation. I've included the parsed down code below along with a picture of what attaching a .pdf file looks like.
Sub AttachDocument()
'create cell location string
Dim celllocation As String
celllocation = ("D6")
'Select the cell in which you want to place the attachment
Range(celllocation).Select
'Get file path
'fpath = Application.GetOpenFilename("All Files,*.*", Title:="Select file")
'If LCase(fpath) = "false" Then Exit Sub
fpath = "C:\Users\Username\Desktop\2019W2.pdf"
'Insert file
Worksheets("Sheet1").OLEObjects.Add Filename:=fpath, Link:=False, DisplayAsIcon:=True, IconFileName:="EXCEL.EXE"
End Sub
I just don't understand why the parameters do not work. Any help is appreciated.
Original Post:
I have code that adds an OLEObject to a worksheet at a specific cell. It works, but I cannot get the parameters for OLEObjects.add method to do anything. The only one that seems to work is "Filename". No matter how I define any of the other parameters the behavior of the macro does not change; I'm not even sure the "Linked" parameter is working and the icon is always dependent on the file type uploaded but does not behave as expected(e.g. word documents do not display word icon, instead a large blank/white square). Ultimately, I want to set the icon to a common icon and define its size. What am I doing wrong here?
Sub AttachDocument()
'Check to make sure there is a selection for table row, if not end macro, also check for selection greater than the number of rows in the table, if yes end macro
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects("RenewablesTable")
If Range("M3").Value < 1 Then
ElseIf Range("M3").Value > tbl.DataBodyRange.Rows.Count Then
Else
'create cell location string
Dim cellnum As Integer, celllocation As String
cellnum = Range("M3").Value + 8
celllocation = ("M" & cellnum)
'Select the cell in which you want to place the attachment
Range(celllocation).Select
'check if cell already has an object if it does end macro
If CheckCellforObject(celllocation) > 0 Then
Else
'Get file path
fpath = Application.GetOpenFilename("All Files,*.*", Title:="Select file")
If LCase(fpath) = "false" Then Exit Sub
'Insert file
Worksheets("Renewable Energy").Unprotect "password"
Worksheets("Renewable Energy").OLEObjects.Add Filename:=fpath, Link:=False, DisplayAsIcon:=True, IconFileName:="excel.exe"
Worksheets("Renewable Energy").Protect "password"
End If
End If
End Sub
Very new to this so please help. Im trying to mass update files in a static folder location, many files in one folder.
What i want to do is
run VBA macro in Excel 2010 to goto a network location folder,
open the first file in the folder.
Unprotect the workbook and worksheets call another marco to run changes
then protect the worksheet close the file
and then move onto the next file in the folder until all files have been corrected.
I have created the marco to make the changes, this is called "Edit"
File types are xlsm and the workbook and worksheet are password protected How can i automatically run the macro to goto the network location and in series open each file, unprotect, call the macro, then re protect the document close file and move onto the next file until they are all updated.
Sub Auto_open_change()
Dim WrkBook As Workbook
Dim StrFileName As String
Dim FileLocnStr As String
Dim LAARNmeWrkbk As String
PERNmeWrkbk = ThisWorkbook.Name
StrFileName = "*.xlsx"
FileLocnStr = ThisWorkbook.Path
Workbooks.Open (FileLocnStr & "\" & StrFileName)
Workbooks(StrFileName).Activate
With Application.FindFile
SearchSubFolders = False
LookIn = "Network location"
Filename = "*.xlsm"
If .Execute > 0 Then
Debug.Print "There were " & .FoundFiles.Count & " file(s) found."
For i = 1 To .FoundFiles.Count
WrkBook = Workbooks.Open(Filename:=.FoundFiles(i))
WrkBook.Worksheets(1).Select
ThisWorkbook.Worksheets(1).Cells(DestinationRange) = WrkBook.Worksheets(1).Cells(SourceRange).Value
Next i
Else
Debug.Print "There were no files found."
End If
Im managing to unprotect the file update and reprotect the file fine, just cant get the file from the network location.
I'm using Excel 07, which doesn't allow Application.FindFile, so I can't test this. However, I believe the issue may be that you need to Set the variable Wrkbook, not just assign it.
Change
WrkBook = Workbooks.Open(Filename:=.FoundFiles(i))
to
Set WrkBook = Workbooks.Open(Filename:=.FoundFiles(i))
and let me know how that turns out!
I am trying to create a button which prompts the user for a file then creates a hyperlink in the active spreadsheet.
Goal: after the file is uploaded subsequent users can click on the hyperlink to view the file.
What I have tried, create an ActiveX control in Excel, but representing the input as a hyperlink output in a cell is the problem.
Private Sub CommandButton1_Click()
Dim sFullName As String
Application.FileDialog(msoFileDialogOpen).Show
sFullName = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
End Sub
Insert reference to pdfs
Sub InsertObjectAsIcon()
'lets user browse for a file to insert into the
'current active worksheet.
'all are inserted as icons, not "visible" objects, so
'to view they will need an appropriate viewer/reader
'at the recipient end.
'
'This one shows how you could set up to use
'several different icons depending on the type of file
'inserted. You'll have to experiment by recording
'macros while inserting various file types to build
'up a list to use, just add new Case Is = statements
'do deal with the file types. Be sure to enter the
'file type in all UPPERCASE.
'
Dim iconToUse As String
Dim fullFileName As String
Dim FNExtension As String
fullFileName = Application.GetOpenFilename("*.*, All Files", , , , False)
If fullFileName = "False" Then
Exit Sub ' user cancelled
End If
'choose an icon based on filename extension
'get all after last "." in filename
FNExtension = Right(fullFileName, Len(fullFileName) - _
InStrRev(fullFileName, "."))
'select icon based on filename extension
Select Case UCase(FNExtension)
Case Is = "TXT"
iconToUse = "C:\Windows\system32\packager.dll"
Case Is = "XLS", "XLSM", "XLSX"
iconToUse = "C:\Windows\Installer\{91140000-0011-0000-0000-0000000FF1CE}\xlicons.exe"
Case Is = "PDF"
iconToUse = "C:\Windows\Installer\{AC76BA86-1033-F400-7761-000000000004}\_PDFFile.ico"
Case Else
'this is a generic icon
iconToUse = "C:\Windows\system32\packager.dll"
End Select
ActiveSheet.OLEObjects.Add(Filename:=fullFileName, Link:=False, DisplayAsIcon:=True, IconFileName:=iconToUse, IconIndex:=0, IconLabel:=fullFileName).Select3
End Sub
Private Sub CommandButton1_Click()
InsertObjectAsIcon
End Sub
This code opens the common file dialog, filtered to show .xslx files. It picks up the path to the file, then inserts it into the activecell. There's also an inputbox asking for a short text name, if you don't want to see the full path.
Sub FileToLink()
Dim strFileName As String
Dim strShortName As String
strFileName = Application.GetOpenFilename("Excel Documents (*.xlsx), *.xlsx")
If strFileName = "False" Then
Exit Sub ' user cancelled
End If
strShortName = InputBox("What do you want to call this link?", "Short Text", strFileName)
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:=strFileName, TextToDisplay:=strShortName
End Sub
You can substitute strFileName = Application.GetOpenFilename("All Documents (*.*), *.*") to show all files. It doesn't matter to the link what file it is, as clicking on the link will invoke the application linked with that file type.
I have this little VBA module that I call from one workbook to update all Excel Workbooks in a given folder. By update I mean it copies a module called GetActiveXControlValues and then runs this macro on each workbook in that folder. Now when I run this on my machine everything works fine. When my co-worker runs this same code with the same files, they gets a surprise after copying the module. When you go to look at the workbook that should have the new module called 'GetActiveXControlValues', instead there is no module by that name, instead it is called 'Module1'. In addition, when you look inside the new module it says 'Attachment has been removed' in red. I checked and my co-worker has the exact same Security Settings in Excel 2010 as I have.
I have enable all Macros and Trust VBA Project Object Model. I have Prompt me for enabling all ActiveX controls. I have Disable Trusted Documents unchecked and all the boxes on the Protected View tab. Anyone seen this before or have an idea what I can try to troubleshoot?
Sample Code:
Sub CopyModuleAndExecuteIt()
Dim wb As Workbook
Dim sFile As String
Dim sPath As String
Dim sFullMacroName As String
SetFolder
sPath = sExcelFolder
ChDir sPath
sFile = Dir("*.xls") ' File Naming Convention
Do While sFile <> "" ' Start of LOOP
' Open each Excel File in the specified folder
Set wb = Workbooks.Open(sPath & "\" & sFile) ' SET BP HERE!
Sleep (1000)
' Unprotect the Documents using SendKeys Hack
UnprotectVBADocument
' Import the GetActiveXControlValues Module into the Workbook
wb.VBProject.VBComponents.Import ("D:\GetActiveXControlValues.bas") ' SET BP HERE!
sFullMacroName = "'" & wb.Name & "'" & "!" & wb.VBProject.VBComponents.Item("GetActiveXControlValues").Name & ".GetActiveXControlValues"
' Run the GetActiveXControlValues Macro
Application.Run (sFullMacroName)
' Close the Workbook Saving Changes
wb.Close True
sFile = Dir
Loop ' End of LOOP
End Sub
If your co-worker has the exact same Security Settings in Excel 2010 as you have then the next thing that comes to my mind is the "Firewall". Check his firewall settings.
I was working to create an AddIn trough VBA code, i wrote the code in a Excel worksheet when i save it, i saved as text like this:
Attribute VB_Name = "Module_Name"
And you have to be sure that you .bas file is actualy is plain text.
I was working to create an AddIn with VBA code, i wrote the code in a Excel worksheet when i save it, i saved as text like this:
Sub Superheroes()
Dim sBeg as string, sEnd as String, sCatwoman as String, sAntMan as String
Dim vCode As Variant
'' Here is where i put the name i want to call my module
sBeg = "Attribute VB_Name = ""VBA_BasFile""" + vbCrLf + _
"Private Function fMix(sAnimal as String)as String "
sCatwoman = "Select case sAnimal"+ vbCrLf+ vbTab+"case ""cat"""+ _
vbCrLf+ vbTab+ "fMix = ""Catwoman"""
sAntMan = vbCrLf+ vbTab+"case ""Ant"""+ vbCrLf+ vbTab+ "fMix = ""AntMan"""+ _
vbCrLf+ "End Select"
sEnd = vbCrLf+ "End Sub"
vCode = Array(sBeg, sCatwoman, sAntMan, sEnd)
Workbooks.add
Range("A1").Resize(UBound(vCode) + 1, 1) = Application.Transpose(vCode)
With ActiveWorkbook
.SaveAs path + "VBA_BasFile.bas", xlTextPrinter
.Close False
End With
End Sub
With this i can Call any procedure or function in the VBA_BasFile when i importe to another Excel Workbook.