Is there a way to programmatically insert formulas into a csv file using vb.net? - vb.net

I need to add formulas to a CSV file that already exists. Is this possible to do this using VB.Net?
The idea is I already have a CSV file and I need one column to be populated in each cell with a custom formula. This has to be done programmatically because these files are being created dynamically.
Does anyone know how to do this? Thanks.

1,2,3,=SUM(A1:C1)
Surprised me when I tried it, but Excel will keep the formula.
You can even export formulas into a CSV by first displaying them on screen.
(Ctrl-`)

While I stand by that my original answer is technically correct, I have been getting a lot of downvotes on this. Apparently popular spreadsheet software such as Microsoft Excel, Open Office, Libre Office Calc will calculate formulas that are entered into a CSV file. However, I would still not recommend relying in this capability.
Original answer:
The CSV format does not support formulas. It is a plain text only format.

You can import formula's into excel via a text file using comma separated values. Just remember to make sure it is named with the suffix .txt.
Then do the import.
My example import ( Data table, From Text)
Column1,Column2,ResultColumn
1,2,=A2+B2
It imported and computed just fine

Are you generating the CSV file? If so, consider writing an actual Excel file. (I'm assuming you're importing into Excel, since you used the term "cell", which has no meaning in CSV.)
Here's a link on how to do it: Create Excel (.XLS and .XLSX) file from C#
If you aren't generating the CSV, and if all you want is to add a new, calculated value,(rather than a formula that will change dynamically as cells change values) you can do this easily enough by reading in the CSV file, parsing each line enough to get the values you need for your formula, calculating the result, and appending it (after a comma) to each line before writing the line out to a new file.

You could open the csv in Excel and then add the formulas to Excel and save back out to csv. You would do this by using the Microsoft Excel 11.0 Object Library. Then
dim wb as Excel.Workbook
dim exApp as New Excel.Application
dim exSheet as Excel.Worksheet
dim rowNum as integer = 1
wb = System.Runtime.InteropServices.Marshal.BindToMoniker(pathAndFileNameOfCSV)
exApp = wb.Parent
exApp.DisplayAlerts = False
exApp.AlertBeforeOverwriting = False
exSheet = exApp.ActiveWorkbook.Sheets.Item(1)
'do your functions in a loop here i.e.
exSheet.Range("A" & rowNum).Value = "=SUM($A$1:$D$4)"
rowNum += 1
wb.Close (True) 'closes and saves
Saving the workbook should convert the formulas back to the values when it is closed.

In Excel, to import formulas with commas the formula must be encapsulated by double quotes to prevent the formula being spread across cells. For example:
2,4,6,13,=sum(A1:C1),"=if(A1=C1,D1-A1,D1+A1)"
Another quirk of Excel is that if you have a string consisting entirely of numbers, you must present it as a formula to retain leading zeros. "00012345" imports as 12345, ignoring the quotes. To import as text, the .CSV file must present this as ="00012345".

Related

VBA - Copying cells across Workbooks

I'm writing a VBA program that changes the visuals of an excel database. At the end, I need to add a "header" (5 rows of text) at the top. The problem is, I cannot insert the text with VBA, since it contains letters (for ex. á, é...) that aren't compatible with VBA, I need to insert that text from another excel file.
The macro I have is stored in a standalone excel workbook, that also contains the cells of the header I need to copy into my database. The problem is, the name of the excel files I am working with varies. Is there a way I could switch between those 2 files and copy cells across them. Can I store the name of the excel file I am working with and later use it in the VBA code to switch between the workbooks?
Not sure if this 100% answers your question but hope it helps, you can open and store both workbooks as objects using:
Dim wb as Workbook, wb2 as Workbook
Set wb = Workbooks.Open("C:\User\Sample_Workbook_File_Path_1.xlsx")
Set wb2 = Workbooks.Open("C:\User\Sample_Workbook_File_Path_2.xlsx")
From there you can call values from either workbook using things like:
'to get the second workbooks excel file name into a worksheet: "Sample_Workbook_2"
wb.Worksheets("Sample_Worksheet").Range("A1").Value = wb2.Name
'to copy files
wb2.Worksheets("Second_Workbooks_Worksheet").Range("A2:A100").Copy _
wb.Worksheets("Sample_Worksheet").Range("A2")
'Alternatively you can store the entire workbooks path name instead of the file name using:
wb.Worksheets("Sample_Worksheet").Range("A1").Value = wb2.Path

How to embed an Excel spreadsheet into a Word Document programmatically using VBA

I have an Excel VBA script that pulls data from a couple of files and builds a table in a certain format that suits the business need. I build the table in a hidden worksheet within my main Excel file and all works as intended.
However, I need to insert that table into a Word file. I know how to make a table, but I wanted to try to do an embedded Excel file instead because that way all of the formatting transfers.
I have created an accompanying Word file with a placeholder embedded Excel object. I gave the object (or "shape") a name in the Selection Pane. It's called InvoiceXLS.
I can get as far as opening the Word document and I know how to change basic OLEShapes / objects such as just changing text in named text boxes, but I can't figure out how to get a usable reference to the embedded sheet so that I can call Excel VBA commands on it, and basically replace it with the table I generated earlier in the script.
So far, this is how I open the link to the Word file:
Set wApp = CreateObject("Word.Application")
wApp.Visible = True
Set wDoc = wApp.Documents.Open(filename:=ThisWorkbook.path & "\TestAccount.docx")
With wDoc
.Shapes("InvoiceXLS").OLEFormat.Edit ' ???
' How do I get a Worksheet object that I can work with??
' Or, just paste in a whole table over top?
End With
Thanks in advance for any help!

Excel macro to save only values of a file with different file names

I wish to save my current excel file as a different file with file name as the value in the cell B10 and taking only values (not formulas) from the current file.
I got the code for getting only values from this link: Saving values from a workbook
Any help appreciated. Thanks.
EDIT:
I want to make a kind of template which will help my colleagues to document in a better way, without wasting disk space in formulas, which takes up about 1.7 mb per *.xls file. If I save only values, it takes about 600 kb. I want it to be flexible to different users, people who won't have to use long instructions to do this.
* vba isn't my area of expertise, and I haven't written any code for this work, so basically any possible way is welcome.
This code will do the need
Sub Macro1()
Dim x As String
Dim y As String
x = "C:\" 'path to file
y = Range("C1").Value 'Reference of the cell which contains the value
Z = x + y
Z = Z + ".xlsm" 'Format of macro enabled worksheet
ActiveWorkbook.SaveAs Filename:=Z, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
End Sub
Since you provided a Text only question, I should give you a Text Only Answer.
To do what you want you have to:
Copy your worksheet using Sheets Object Copy method. It has optional arguments and if you omit it, it automatically creates a new workbook that contains the copied worksheet.
After copying, you can use ActiveObject (e.g. ActiveWorkbook, ActiveSheet etc.) to make reference to your newly created workbook and worksheet.
Once you have referenced the objects properly, you can now use Cells property to select all ranges and copy. Then use Range PasteSpecial Method to convert formulas to values.
Lastly you'll need to save the workbook using the Workbook Object SaveAs Method.
Hope this somehow leads you to a solution. HTH.

Excel macro to make a csv for worksheet with unicode data

I am using a macro for making a csv file for each worksheet in my xlsm file.
The is unicode data with around 50000 rows and some columns have dates in them.
By going through cell by cell and appending that data to the csv file is
taking a lot of time.
Can you please suggest me some ways to create a csv file for unicode worksheet with large data?
Excel has the ability to save as a csv file built in already: there is no need for you to code this explicitly. And that will be faster than anything you could code in VBA.
The easiest way to discover how is to use the macro recorder (available on the developer tab) and save your file as a csv.
Just put the values in an array, and then paste it to the worksheet.
Set TheRange = Range(Cells(1, 1), Cells(50000, 100))'Set worksheet range
ReDim TempArray(1 To 50000, 1 To 100)
' Fill the temporary array here
->some code to fill our "TempArray"<-
' Copy array to worksheet
TheRange.Value = TempArray

Excel: Save as csv via vba and manually results in a different file

I need to save several xlsm files as CSV in order to import them in other programs (such as R etc.). Well I've written the necessary import routines in all the other programs and they work very nicely with case 1:
Case 1: Manually saving an xlsm as CSV
If I use this option and manually save each file as CSV and click YES on all prompts, I get a .csv file which looks very similar to a normal Excel file when opened again within excel. It is a standard column view, and nothing comma separated etc. (maybe it is, but it doesn't look that way..)
Case 2: Saving an xlsm from VBA as CSV
Well here I get a completely different file when opened again in Excel. This one looks like a "real" csv file with all values being comma separated.
My questions are:
1. Why is there any difference?
2. How can I programmatically reach Case 2 from VBA? Or is that impossible?
If 2 is impossible I have to rewrite my import code routines to handle the "normal" csv file...not very difficult but still a lot of work and I'm really wondering why there even is a difference..
Q1: I don't think there is a difference, at least not in an example I pulled together. Q2: Try this out:
I've got 3 example XLSM files in C:\stack\folder1 as pictured below:
Each file has a single data sheet, which we'll turn into CSVs:
I'm sure your routine is much more complicated, but to test the CSV output I'm just going to loop through the files and save each as xlCSV:
Option Explicit
Sub TestCSVOutput()
Dim DataBook As Workbook
Dim DataSheet As Worksheet
Dim FilePaths(3) As String
Dim FileIdx As Long
'set up file paths for test
FilePaths(1) = "C:\stack\folder1\test_file_01.xlsm"
FilePaths(2) = "C:\stack\folder1\test_file_02.xlsm"
FilePaths(3) = "C:\stack\folder1\test_file_03.xlsm"
'loop through array and save each file as a CSV
Application.DisplayAlerts = False
For FileIdx = 1 To UBound(FilePaths)
Set DataBook = Workbooks.Open(FilePaths(FileIdx))
Set DataSheet = DataBook.ActiveSheet
DataBook.SaveAs FileFormat:=xlCSV '<~~ the save step
DataBook.Close
Next FileIdx
Application.DisplayAlerts = True
End Sub
Once the script completes, I end up with three CSV files:
Each file is comma-delimited when opened in a text editor: