I need to save the txt file, which is embedded as an object in the Excel workbook.
I had a look at Saving embedded OLE Object (Excel workbook) to file in Excel 2010.
In the workbook, I have an embedded text file and pdf files (for test purposes, but ultimately I need to use txt file). When I point the OLEObject to xlsm and update the fName accordingly, the below command works correctly.
But when I point the OLEObject to txt file and change the extension in fName to txt, it fails with
Run-time error 1004.
What is the command for txt files? I tried SaveAs2 as per the other threads.
Dim uName As String
Dim fName As String
Dim oEmbFile As Object
uName = Left(Environ("AppData"), Len(Environ("AppData")) - 16)
fName = uName & "\Desktop\OTPReport_Vin" & ".xlsm"
Set oEmbFile = wbkCurrent.Worksheets("Compare the changes").OLEObjects("Object 1")
oEmbFile.Object.SaveAs fName
You need to specify the format, not just change the extension.
Here's the list of different ones (though I don't think it is fully complete):
https://learn.microsoft.com/en-us/office/vba/api/excel.xlfileformat
You would want xlTextWindows so your code would be:
oEmbFile.Object.SaveAs fName, xlTextWindows
Related
At work, I'm writing a macro. The summary of the macro's function is as follows:
User inputs SharePoint Link
Macro downloads file from link
Macro opens file
Macro copies data from downloaded file, pastes into the original file and sets up formulas, formatting, etc in the original file
The issue lies in step 2. Once the macro tries to open the downloaded file, I get the following error:
"Excel cannot open the file 'temp.xlsx' because the file format or extension is not valid. Verify that the file has not been corrupted and the file extension matches the format of the file."
When I end the macro and try to open up the file manually, I get the same error, so the issue lies with the file itself.
I have tried saving the file in different formats. Excel throws the same error when I download as a .xlsm. When downloaded as a .xls, the file turns up blank. If downloaded as a .txt, the text is just info of the file I downloaded, not the data.
If someone has an alternative way to get data from a Sharepoint file instead of a fix to the error, that would be great as well!
Below is steps 1-3 of my code:
'Input box + declarations
Dim myValue As String
myValue = InputBox("Enter Sharepoint Link")
'Declarations
Dim i As Integer
Dim strURL As String
strURL = myValue
Dim strSavePath As String
Dim returnValue As Long
'userName is entered in a cell because different users may be running the macro, but we do not want to have to prompt the user to enter their username every time
Dim userName As String
userName = Sheets("Reference").Range("B4").Text
Dim Path As String
Dim R As Range
Dim R2 As Range
'Set dynamic path and save
strSavePath = "C:\Users\" & userName & "\OneDrive - Ingredion\Desktop\temp.xlsx"
returnValue = URLDownloadToFile(0, strURL, strSavePath, 0, 0)
'open workbook and copy cells
Workbooks.Open strSavePath```
I'm trying to get a macro that works perfectly in Excel 2011 for Mac to work in Excel 2016 for mac. The goal is to have the user specify a folder with .csv files in it, and then the macro loops through all the .csvs, opening each to copy information out of it into another Workbook.
The macro fails when trying to open the first .csv file in the user-chosen folder, with a 1004 error, file cannot be found.
(side note: Earlier in the macro, workbooks.open works perfectly with a user selected FILE)
The macro is huge, so I made a brand new smaller one just to get past this problem. Here is the smaller, test code, which has the same failing behavior:
Sub Test()
Dim folderpath As Variant
Dim filename As Variant
Dim newfilename As Variant
Dim wb As Workbook
Dim newfolderpath As Variant
folderpath = MacScript("choose folder as string")
newfolderpath = Replace(folderpath, ":", "\")
MsgBox (newfolderpath)
filename = MacScript("Choose file as string")
newfilename = Replace(filename, ":", "\")
MsgBox (filename)
MsgBox (newfilename)
MsgBox (Dir(filename))
MsgBox (newfolderpath & Dir(filename))
Set wb = Workbooks.Open(newfolderpath & Dir(filename))
End Sub
All the msgboxes provide expected values.
newfolderpath= the whole path with \ separators.
filename= the whole path and file name with : separators.
newfilename= the whole path and file name with \ separators.
Dir(filename)= just the file name.
newfolderpath & Dir(filename))= the entire path and file name with \
separators.
Set wb line gives:
Run-time error '1004'
'Hard DRIVE\USERS\DAVE\DESKTOP\CSVS\1.CSV'
could not be found.
Clearly the file is there, openable and works.
Any help is greatly appreciated.
Well, I think I found the answer, or at least an answer that works for my project.
I went back to the workbooks.open(user-selected FILE) from earlier in the macro, and discovered it was reading it as "/users/Dave/Desktop/csvs/1.csv". So, even though debug and msgbox were returning backslashes, it was somehow wanting forward slashes (You were partially right, Tim). Additionally, it clearly truncates the name of the Mac hard drive, and starts with the users directory. So, I just modified the variables to match this format, and voila, it worked. For those who are interested, here's the modified code I wound up using:
Sub Test()
Dim folderpath As Variant
Dim newfilename As Variant
Dim wb As Workbook
Dim newfolderpath As Variant
Dim newfp As Variant
folderpath = MacScript("choose folder as string")
newfolderpath = Replace(folderpath, ":", "/")
newfp = Right(newfolderpath, Len(newfolderpath) - InStr(newfolderpath, "/") + 1)
newfilename = Dir(newfp)
Set wb = Workbooks.Open(newfp & newfilename)
Exit Sub
Thanks to everyone that helped.
If FileUpload.HasFile Then
Dim FileNameXlsx = Path.ChangeExtension(Path.GetFileName(FileUpload.PostedFile.FileName), ".xlsx")
Dim pathOfUploadedCCP As String = Server.MapPath("~/Uploaded/Documents/TemporaryUploadedFileForCCP/") + FileNameXlsx
FileUpload.SaveAs(pathOfUploadedCCP)
This code only changes the extension but I am getting the error that the file is corrupted. Please help me: How do I change the format of files to excel workbook (.xlsx)?
Refer below link, this may help you.
https://www.gemboxsoftware.com/spreadsheet/articles/convert-xls-xlsx-ods-csv-html-net
As I can see in example, you need to include their library in your project.they have given example you can check it by using below link.
https://www.gemboxsoftware.com/spreadsheet/examples/c-sharp-convert-excel-to-pdf/404
The XLS and XLSX file formats are different file formats. You cannot just change the extension. The following example is an extreme analogy, but let's say that you want to change a text file (TXT extension) to image file (PNG extension).
When you will try to open the file, MS Excel recognize the invalid format and this is the error that you get.
You must convert your xls file to xlsx file format.
You can use an Excel library like EasyXLS to achieve this goal:
Dim workbook As New ExcelDocument
'Load the xls file
workbook.easy_LoadXLSFile(FileNameXls)
'Convert the xls file to xlsx file
workbook.easy_WriteXLSXFile(FileNameXlsx)
Can you do this?
Dim myFiles As String()
myFiles = IO.Directory.GetFiles("<Folder Location of thge File>", "*.xls")
Dim newFilePath As String
For Each filepath As String In myFiles
newFilePath = filepath.Replace("<Folder Location of thge File>", ".xlsx")
System.IO.File.Move(filepath, newFilePath)
Next
End Sub
It will replace the file extension of a file in a folder if the program find an extension of .xls
If the code above wont work try this.
Dim Path as String
Path = "C:\Programs\And_So_On\"
Dim Final As String
Final = Path & "YourFile.xlsx"
YourWorkBook.SaveAs(Final)
I am trying to save an embedded OLE Object (Excel workbook) from my current/open workbook to a location on the user's PC. This OLE object is a template/dashboard that gets populated during the execution of the macro.
The macro first tests if the file exists on the user's C drive.
If it does exist, it opens that file and sets a workbook variable to this newly opened workbook. This works in both Excel 2010 and Excel 2013.
Where the user does NOT have the file saved to their C drive, the macro opens the OLE object to save it to drive. The macro then points back to that location and opens the file. The code works in Excel 2013, however in Excel 2010, the macro crashes Excel when I try to save the file to the drive. If I run the macro in break mode, saving works, it is only during run-time that there is a crash.
Could there be a possible use of DoEvents or Application.Wait here?
Some things that I've noticed:
The crash does not generate any error code. It simply gives "Has stopped responding".
I've tried multiple versions of .SaveAs fileformat:=52 vs .SaveCopyAs. Both methods produce the same crash in 2010.
The OLE object opens as "Worksheet in", it would be nice if this opens in a new workbook. I'm thinking this crash could be related to how the object is opened as a "Worksheet in" rather than it's own workbook.
Code:
Dim uName As String
Dim fName As String
Dim wbk As Workbook
Dim sumWB as Workbook
Dim cbrWB as Workbook
Set cbrWB = Workbooks("PreviouslySet")
uName = Left(Environ("AppData"), Len(Environ("AppData")) - 16)
fName = uName & "\OTPReport" & ".xlsm"
If Dir(fName) = "" Then
Set oEmbFile = cbrWB.Worksheets("CBRDATA").OLEObjects("OTPReport")
oEmbFile.Verb 0
For Each wbk In Workbooks
If InStr(1, wbk.Name, "Worksheet in", vbTextCompare) > 0 And InStr(1, wbk.Name, Left(cbrWB.Name, Round(Len(cbrWB.Name) / 2)), vbTextCompare) > 0 Then
Set sumWB = Workbooks(wbk.Name)
End If
Next wbk
With sumWB
.Activate
.Application.DisplayAlerts = False
'==ISSUE EXISTS HERE==
.SaveCopyAs (fName)
.Close
End With
Set sumWB = Nothing
Set sumWB = Workbooks.Open(fName)
Else:
Set sumWB = Workbooks.Open(fName)
End If
Use the actual embedded COM object instead of the default action that .Verb 0 gives you.
OLEObjects expose a reference to the underlying object if they are being administered by a COM server (it's the .Object property). In your case, since you have an embedded workbook, it's just a Workbook object like any other Workbook object you'd encounter in VBA. All you should need to do is call .SaveAs on it:
oEmbFile.Object.SaveAs fName
Then you can simply skip the rest of the gymnastics related to trying to find it in your current Excel server.
Posting my solution here to show what seems to be working in both 2010 and 2013. This solution was developed with the help of user COMIntern. I will give credit for this solution to his answer.
Updated code w/ explanation:
Dim uName As String
Dim fName As String
uName = Left(Environ("AppData"), Len(Environ("AppData")) - 16)
fName = uName & "\OTPReport" & ".xlsm"
If Dir(fName) = "" Then
Set oEmbFile = cbrWB.Worksheets("CBRDATA").OLEObjects("OTPReport")
oEmbFile.Object.SaveAs fName
'For some reason a new workbook named "BookN" (n = to some integer) is created when
'saving our embedded file to C. To counter this, I close the most recently opened workbook.
Workbooks(Workbooks.Count).Close
'When opening this workbook, the file shows that it is opened, but the window is not activated.
'We must use the name of the file and call activate to get it to show up in our active windows.
Set sumWB = Workbooks.Open(fName)
Windows("OTPReport.xlsm").Activate
Else:
'same explanation as above
Set sumWB = Workbooks.Open(fName)
Windows("OTPReport.xlsm").Activate
End If
I'm using the following code to open multiple xml files, however they are opening as a read only workbook, however I require it to open as an XML table, any suggestions?
Code:
Sub AllFolderFiles()
Dim wb As Workbook
Dim TheFile As String
Dim MyPath As String
MyPath = "C:\Documents and Settings\"
ChDir MyPath
TheFile = Dir("*.xml")
Do While TheFile <> ""
'Call Logs 'This calls for Macro2 to run
Set wb = Workbooks.Open(MyPath & "\" & TheFile)
MsgBox wb.FullName
'wb.Close
TheFile = Dir
Loop
End Sub
You need to use Workbooks.OpenXML instead
Set wb = Workbooks.OpenXML(Filename:=MyPath & "\" & TheFile, LoadOption:=xlXmlLoadImportToList)
I'm not exactly which LoadOption you want to use, but you can choose from:
xlXmlLoadImportToList Automatically creates an XML List and imports
data into the list.
xlXmlLoadMapXml Loads the XML file into the XML Source task pane.
xlXmlLoadOpenXml Open XML files in the same way that Excel 2002
opens XML files (for backwards compatibility only).
xlXmlLoadPromptUser Prompts the user and lets them choose the Import
method.