Execute macro commands in csv files or create a macro that transforms the file into csv - excel

I have a file with a table of info and information about the entry. In the table I have columns, one column in the table is the social security number, the ID number in my country is 9 digits. Often the ID number begins with a 0 - digit number. The Excel always omits the number 0, I wrote a macro code that adds 0. But I end up converting the file to CSV, after converting it again omits the number 0. I want to know how I execute my macro code in CSV (which disappeared 0 - I will be happy to set up the macro on csv files or at least execute a macro that converts the file into a .csv file and saves the 0 that disappear. Here is my command that works on xslm:
Sub Add_Zeros()
Selection.NumberFormat = "#"
For Each CL In Selection.Cells
If CL <> "" Then CL.Value = Application.Rept("0", (9 - Len(CL))) & CL
Next
End Sub

The Csv will have the 0. You can check that by opening it in notepad. If you double click on the CSV and open it in Excel then the 0s will disappear.
To preserve the 0s, you will have to import the data directly in Excel. Follow the steps mentioned below.
Click on Data Tab | From Text
Select the Csv from the file slection dialog box
In text Import Wizard (STEP 1), select 'Delimited' and hit next.
In text Import Wizard (STEP 2), select 'Comma' and hit next.
In text Import Wizard (STEP 3), select all columns and click on 'text' in the 'column data format'
Click finish
Select the cell where you want to import the data and click 'ok'

Related

Excel sheet.range().Value holding wrong data

I am trying to take data from an Excel sheet named range and import it to an Access database. However, one range, with text data, is input by a dropdown list. For some reason, it somehow gets turned in data Variant(1 to 1).
Watch window:
+
xlx.Range("Talk_codes").Value(7)
Variant(1 to 1)
Form_Logs.GetRangeNames
Select Case xlx.Range("Talk_codes").Value
Case "Show ID"
Logs.Show_Promo = Logs.Show_Promo + DateAdd("s", xlx.Range("Talk_Time").Value, Logs.Show_Promo)
I know the first cell, at least in the cells, is "Show_ID".
Any suggestions to force it to have the actual data?

VBA or function to connect 2x CSV files into 1x XLSX

Greets,
I got this scenario with 3x different files;
1) one CSV file has Column A (-first row) with abbreviations that needs to be copied on XLSX file (also in Column A)
+
2) another CSV has many rows and column where is explanation for the first case (abbrevations), and I have to look for explanation inside that big file (so vlookup I used).
=
3) xlsx file is separate that has to combine both CSV into one, where on Column A I will have abbreviations and on Column B explanations of the certain terms.
I tried with functions and simply defining ranges:
Column A1 ='C:\Users\MirzaV\Desktop\1\[0528-matrix.csv]0528-matrix'!A3
Column B1 =VLOOKUP(A1;'C:\Users\MirzaV\Desktop\1\[variantendb.csv]variantendb'!$C:$D;2;0)
So seems nothing hard or else, but problem is I am having XXX of these CSV files and one main CSV file with explanations (it is stated as "varianten") , that are gonna be updated periodically - all of the files.
Instead to open three files at the same time just to refresh my functions, is it a bit quicker way with a code or other functions?? And I would like to have it in XLSX file.
I tried to record a macro but it didnt work good, I was thinking I can use it for rest of the files but always gives an error.
Application.Left = 2318.5
Application.Top = 89.5
Windows("0528-matrix1.xlsx").Activate
Range("A1").Select
ActiveCell.FormulaR1C1 = "='0528-matrix.csv'!R[1]C"
Range("A1").Select
Selection.AutoFill Destination:=Range("A1:A500"), Type:=xlFillDefault
Range("A1:A500").Select
ActiveWindow.Close
ActiveWindow.ScrollRow = 1
Application.Left = 2161
Application.Top = 1
Application.Width = 720
Application.Height = 780
Windows("0528-matrix1.xlsx").Activate
Range("B1").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[-1],variantendb.csv!C3:C4,2,0)"
Range("B1").Select
Selection.AutoFill Destination:=Range("B1:B500")
Range("B1:B500").Select
Application.Left = 1896.25
Application.Top = 32.5
Application.Width = 864
Application.Height = 493.5
Windows("variantendb.xlsx").Activate
ActiveWindow.Close
Application.Left = 1669
Application.Top = 1
ChDir "C:\Users\MirzaV\Desktop\1"
Since you're using Office 365 we can use the Get & Transform feature to create links to your CSV files. As long as you maintain the same filenames on the CSVs, this will enable Excel to automatically update the data.
We'll complete this data merge in 3 stages:
Link the reference CSV (the second file you have listed) to a table
Link to the data CSV (the first file) to a table
Write an Index/Match function to pull the descriptions.
Stage 1: Linking the reference file to a table
In a new Excel workbook, click on the Data tab, then click on the New Query dropdown in the Get & Transform section. Mouse over "From File >" and select "From CSV"
Navigate to CSV 2 and click Import
On the next window that pops up, click "Load"
Your lookup data will now load into a table on a new sheet. Now let's clean up the references here:
Click on the Formulas tab, then Click on Name Manager
Select your new table (it will be named the same as your file)
Change the name to "Reference" and click Ok.
Go to your table and change the column names from "Column 1" and "Column 2" to "Abbr" and "Desc"
And that's it for stage 1! Now that we have the reference table set up and linked, we can move on to loading the data table we want to find the descriptions for.
Stage 2: Linking the data file to a table
We're going to link to the data file in the same way we did the reference file. Go to Data > Get & Transform > New Query > From File > From CSV. Select your file and click Import, then click Load.
On the new table, rename Column 1 to "Code" (I would use Abbr, but Code will help keep the next step looking clear).
Add another column to this table. The simplest way is to just click in B1, type "Desc" (or whatever name of your choosing) and hit Enter.
Stage 3: The Index function that makes the magic
On your new data table with the blank description column, click in the first data cell.
Type in the function =INDEX(Reference[Desc],MATCH([#Code],Reference[Abbr],0)) and press Enter.
Watch the magic happen as Excel copies our formula to every cell in that table column!
By setting up our CSV files as external connections in this manner, we're able to create a dynamic table that will always update with the CSVs.
By using Index/Match, we're able to get away from the constraints of VLookup (data in left-most field, sorted alphabetically), and move to a system that allows us to look for the value we need from any field in any order.
Breaking it down, Index returns the value of the cell provided in the target row and column of the specified array or table. Because we specified the target array as a single column of data, we can use Index([array], [row number]), or using the code above Index(Reference[Desc], [row number]). What really makes this work is the use of Match. Match returns the row number in an array of a target value, so we use MATCH([#Code],Reference[Abbr],0). This returns the row number to Index, which then pulls the data from the desired cell.
There are some additional steps we can do using the Power Query Editor to ensure the column headers always stay the same, but that's a tutorial for a different day. Hope this helps!

VBA - The code to complete 0 is missing after converting a file to csv format

I have 2 commands to add 0 to number (8 digits, 9 digits required), and 0 addition to cell phone numbers (9 digits beginning with 5 digits need to be 10 digits):
1.Add 0 to 8 digits :
Sub Add_Zeros()
Selection.NumberFormat = "#"
For Each CL In Selection.Cells
If CL <> "" Then CL.Value = Application.Rept("0", (9 - Len(CL))) & CL
Next
End Sub
2.Add 0 to 9 digits :
Sub Add_Zeros()
Selection.NumberFormat = "#"
For Each CL In Selection.Cells
If CL <> "" Then CL.Value = Application.Rept("0", (10 - Len(CL))) & CL
Next
End Sub
**1.**First, can I upgrade these codes and combine them as follows?:
A.The first condition: If there are only 8 digits you will add 0 at the beginning (Finally there should be 9 digits)
B.The second condition: If there are 9 digits and the first digit on the left is 5 you add 0 at the beginning (Finally there should be 10 digits)
C.Something else how do I return the command back (ie before the change) to cancel? Do you have a way to insert this into another code?
**2.**In addition, I'm looking for a way to run a code (if it's a VBA or something else) that will convert my Xltm file (after running all the commands) to a .csv file and save me the 0 (zeros) I add.
That the final code for converting the file would be built like this:
A. Make Xltm for csv and keep me the 0 (zero) according to the following law (which is the way to keep the zeros):
1.Click on Data Tab | From Text
2.Select the Csv from the file slection dialog box
3.In text Import Wizard (STEP 1), select 'Delimited' and hit next.
4.In text Import Wizard (STEP 2), select 'Comma' and hit next.
5.In text Import Wizard (STEP 3), select all columns and click on 'text' in the 'column data format'
6.Click finish
7.Select the cell where you want to import the data and click 'ok'
B. After that save me the file as Xlsx.
*C.If you can add another action in the code that also:
Change the extension of the Xlsx again to csv, it is excellent (not save as csv but only change the extension of the file)
The file is attached Link :
Work file
(check that extension Xltm)
Thanks in advance,
Blessed be from heaven
Regarding question 1:
I'm not following your explanation fully, but this will hopefully get you started:
Sub Add_Zeros()
Selection.NumberFormat = "#"
For Each CL In Selection.Cells
If CL <> "" Then CL.Value = ZeroPad(CL) ' Move the logic to a function for better readability
Next
End Sub
Function ZeroPad(Value)
ZeroPad = Value ' Make sure you have a return value
If Len(Value) <= 8 Then 'Pad with zeroes up to 9 chars
ZeroPad = Right("000000000" & Value, 9)
End If
If Left(Value, "5") Then ' I didn't understand your question here. Just guessing
ZeroPad = Right("000000000" & Value, 10)
End If
End Function
Regarding question 2:
As it is currently worded, it is not a question for StackOverFlow. I suggest you remove that part and have a look at https://stackoverflow.com/help/mcve

CSV files: excel hiding zeros

if I load a csv file into excel, value 123.320000 will become 123.32.
i need to view all contents as they are. any way to stop excel from hiding trailing zeros?
reading other posts, i found that doing something like this could work "=""123.3200000" but that would mean running regex on the file every time i want to view it.. since it comes in xxxx|###|xxx format and i have no control over the generation part.
How exactly are you loading the CSV file?
If you import it as "Text" format then Excel will retain all formatting, including leading/trailing zeros.
In Excel 2010 you import from the "Data" tab and choose "From Text", find your CSV file then when prompted choose to format the data as "Text"
I'm assuming that once the imported values are in the sheet, you want to treat them as numbers and not as text, i.e. you want to be able to sum, multiply, etc. Loading the values as text will prevent you from doing this -- until you convert the values back to numbers, in which case you will lose the trailing zeros, which brings you back to your initial conundrum.
Keeping in mind that there is no difference between the values 123.32 and 123.3200000, what you want is just to change the display format such that the full precision of your value is shown explicitly. You could do this in VBA like so:
strMyValue = "123.3200000"
strFormat = "#."
' Append a 0 to the format string for each figure after the decimal point.
For i = 1 To Len(strMyValue) - InStr(strMyValue, ".")
strFormat = strFormat & "0"
Next i
With Range("A1")
.Value = CDbl(strMyValue)
.NumberFormat = strFormat
'Value now shown with same precision as in strMyValue.
End With

Using VBA, how can I select every other cell in a row range (to be copied and pasted vertically)?

I have a 2200+ page text file. It is delivered from a customer through a data exchange to us with asterisks to separate values and tildes (~) to denote the end of a row. The file is sent to me as a text file in Word. Most rows are split in two (1 row covers a full line and part of a second line). I transfer segments (10 page chunks) of it at a time into Excel where, unfortunately, any zeroes that occur at the end of a row get discarded in the "text to columns" procedure. So, I eyeball every "long" row to insure that zeroes were not lost and manually re-enter any that were.
Here is a small bit of sample data:
SDQ EA 92 1551 378 1601 151 1603 157 1604 83
The "SDQ, EA, and 92" are irrelevant (artifacts of data transmission). I want to use Excel and/or VBA to select 1551, 1601, 1603, and 1604 (these are store numbers) so that I can copy those values, and transpose paste them vertically. I will then go back and copy 378, 151, 157, and 83 (sales values) so that I can transpose paste them next to the store numbers. The next two rows of data contain the same store numbers but give the corresponding dollar values. I will only need to copy the dollar values so they can be transpose pasted vertically next to unit values (e.g. 378, 151, 157, and 83).
Just being able to put my cursor on the first cell of interest in the row and run a macro to copy every other cell would speed up my work tremendously. I have tried using ActiveCell and Offset references to select a range to copy, but have not been successful. Does any have any suggestions for me? Thanks in advance for the help.
It's hard to give a complete answer without more information about the file.
I think if your input data is 2200+ pages long, it's unlikely that opening it with the default excel opening functions is the way to go. Especially since Excel has maximum number of rows and columns. If the file is a text file (.txt) I would suggest opening it with VBA and reading each line, one at a time, and processing the data.
Here's an example to get you started. Just keep in mind that this is transposing each row of text into columns of data, so you will quickly fill all the columns of excel long before you run thru 2200 pages of text. But it's just an example.
Sub getData()
dFile = FreeFile
sFile = "c:\code\test.txt"
Open sFile For Input As #dFile
c = 1
'keep doing this until end of file
Do While Not EOF(dFile)
'read line into dataLine
Input #dFile, dataLine
' break up line into words based on spaces
j = Split(dataLine, " ")
jLength = UBound(j)
If jLength > 2 Then
r = 1
'ignore first 3 words
'and get every other word
'transpose rows of text into columns
For word = 3 To jLength Step 2
Cells(r, c) = j(word)
r = r + 1
Next word
End If
c = c + 1
Loop
Close #Data
End Sub

Resources