Change Excel file Format ( from .xls to .xlsx) through vb - excel

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)

Related

How to save a workbook using a value from a referenced cell as the file name?

I am trying to save a workbook with the value from a cell as the file name.
This code will save it as a specific file name,
ActiveSheet.SaveAs FileName:="C:\Desktop\temp1"
I need to use a unique file name based on what is in the file.
I tried the following, but receive
runtime '1004' error
stating that the file could not be accessed.
Sub Save_Workbook()
' Saves workbook as filename
Dim FileName As String
Dim Path As String
Path = "C:\Desktop\"
FileName = Range("K5").Value & ".xlsm"
ActiveWorkbook.SaveAs Path & FileName, xlOpenXMLWorkbookMacroEnabled
End Sub
The issue turned out to be the formatting of the contents of the target cell. Part of the string in the cell was 12:01. Once this was changed to 12.01, the issue was resolved.

Error when trying to download file from SharePoint URL and open it

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```

Open saveas dialog box for another workbook

I am currently working on a temporary solution but run into a problem....
The situation is:
I have a converter built in Excel, that opens up a XLS File, does some tinkering so the file can be uploaded to an Oracle Database.
The problem is, the XLS file I opened I cannot get the Saveas Dialog box to that file, it always saves a copy of the converter instead.
What I need to happen is to open the Saveas Dialog box in a filepath set the file filter for CSV, for the file that i have opened.
RRBOOK.Activate The RR Book is the DIM'd file i opened
Dim FileName As String
FileName = Application.GetSaveAsFilename("\\FILEPATH\", FileFilter:="CSV (Comma delimited) (*.csv), *.csv")
If FileName <> "False" Then
ActiveWorkbook.SaveAs FileName
End If
Any help would be appreciated!
Avoid using ActiveWorkbook and .Activate.
Instead directly save the desired workbook by
RRBOOK.SaveAs FileName
Also you should specify the file format you wish to save in according to XlFileFormat enumeration and Workbook.SaveAs method.
So for saving as CSV you should eg use
RRBOOK.SaveAs FileName, xlCSV
So you would end up with something like
Dim FileName As Variant
FileName = Application.GetSaveAsFilename("\\FILEPATH\", FileFilter:="CSV (Comma delimited) (*.csv), *.csv")
If VarType(FileName) = vbBoolean And FileName = False Then
'user pressed cancel
Exit Sub
Else
RRBOOK.SaveAs FileName
End If

How to save an embedded txt file?

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

Excel VBA code to bulk convert rtf files in a folder to pdf files

I am a novice to VBA coding, but would like to know how to create a macro in excel that allows me to choose a folder in which there are rtf files, and convert them all to pdf within the same folder.
Any help is appreciated.
Kind regards
The simplest way to do this is to use Word to open the .rtf and convert it to PDF. Excel is designed to display spreadsheets not documents, but you can automate this from Excel by referencing the Word object library.
Use the built-in FileDialog to prompt you for folder selection, and as an entry point to the macro.
'Add a Reference Microsoft Word Object Library
Sub ConvertRtfToPDF()
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
If .Show() Then
ConvertFiles GetFiles(.SelectedItems(1), ".rtf")
End If
End With
End Sub
This is the function that does the conversion, it takes an array of files and converts them all to PDF:
Sub ConvertFiles(files() As String)
Dim wd As New Word.Application
Dim doc As Word.Document
Dim file As Variant
For Each file In files
Set doc = wd.Documents.Open(file, ReadOnly:=True)
doc.ExportAsFixedFormat Replace(file, ".rtf", ".pdf"), 17
doc.Close
Next file
wd.Quit
End Sub
This function returns an array of filenames, given a folder name:
Function GetFiles(folder As String, extension As String) As String()
Dim files() As String
ReDim files(0)
file = Dir(folder & "\")
While (file <> "")
If Right(file, Len(extension)) = extension Then
files(UBound(files)) = folder & "\" & file
ReDim Preserve files(UBound(files) + 1)
End If
file = Dir
Wend
ReDim Preserve files(UBound(files) - 1)
GetFiles = files
End Function
Paste all that into a module and run the ConvertRtfToPDF function, you will be prompted to select a folder and it will convert every .rtf in that folder to a .pdf.

Resources