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

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

Related

How to Eliminate Unwanted Text in an Excel Column with Multiple Rows

First I apologize if this question is addressed elsewhere.
Anyway I recently downloaded an excel table with people indicating their race. So if you are Asian you checked "Asian". When I downloaded the data each cell comes with information like Checked:Asian, Unchecked: White, Unchecked: Black, etc,...
See image column highlighted in yellow.
As you can imagine I want the column to only have Checked: Asian and not the other stuff I am not interested in
Question: How do I eliminate the junk?
I tried to use text to columns feature in Excel but it kept only the first column, which I do not want because some of the checked data is in the 3rd or 4th columns.
I already contacted the the app web managers and the response I got was ..sorry that is the way our software works and you will just have to clean it up
yourself Needless to say pretty #$#*&&!! up.
[Google Spreadsheet with Data: Please click the Sheet name "Race" on the Workbook2
Put this formula in a blank column and copy down:
=IFERROR(SUBSTITUTE(FILTERXML("<a><b>"&SUBSTITUTE(B2&" UNCHECKED:",":","</b><b>")&"</b></a>","//b[contains(.,'UN')=false]/following-sibling::*[1]")," UNCHECKED",""),"")
I've put together a VBA function for you that pulls out the "Checked" piece of text. It starts by seeing if the data starts with "CHECKED", in which case it gets the text up to the start of the first "UNCHECKED". If not, then it looks for " CHECKED" (with a space), and again gets the text up to the next "UNCHECKED". It then removes the "CHECKED: " text at the start of the string.
Function fExtractChecked(strData As String) As String
If Left(strData, 7) = "CHECKED" Then
strData = Left(strData, InStr(strData, "UNCHECKED") - 1)
fExtractChecked = strData
ElseIf InStr(strData, " CHECKED") > 0 Then
strData = Mid(strData, InStr(strData, " CHECKED"))
If InStr(strData, "UNCHECKED") > 0 Then
strData = Left(strData, InStr(strData, "UNCHECKED") - 1)
End If
fExtractChecked = strData
End If
If Len(fExtractChecked) > 0 Then
If InStr(fExtractChecked, ":") > 0 Then
fExtractChecked = Mid(fExtractChecked, InStr(fExtractChecked, ":") + 1)
End If
End If
fExtractChecked = Trim(fExtractChecked)
End Function
Just paste the function into a new module, and you can then use this function just like any built-in Excel function, so if your data is in cell B1, you would type this into cell C1:
=fExtractChecked(B1)
Regards,

How to read multiple text files (with multiple lines of data) into a two dimensional array?

DESCRIPTION:
I have 10 text files. And I want to read them into a two dimensional array. Each file looks like this and the number of lines vary. There are 5 lines in this text file but other text files may have more or less than 5 lines.
No. Location(ft) Mix Near Far Comp. Height(ft) B(in) D(in) Angle(degrees)
1 (0.8127,8.66) 35 MPa true true true 9.17 10 36 0
2 (0.8333,60.67) 35 MPa true true true 9.17 10 36 0
3 (0.8333,80.42) 35 MPa true true true 9.17 10 36 0
4 (14.19,26.22) 35 MPa true true true 9.17 10 24 0
The first dimension of the array will contain each of line the text file. The second dimension of the array will be each text file.
So something like this
Redim TotalArray(1 to 1000, 1 to 10)
1000 is definitely more than the number of lines that I have. 10 is for the 10 text files
FINAL PURPOSE:
The last step would be further split the columns of each text file. In other words, I may need a three dimensional array? However, I am testing the codes for the two dimensional array first. I just state my final purpose in case my approach will be futile and you guys can suggest something better.
My codes are as follows
Sub GetFile()
'Loop through all files in a folder
Dim fileName As String
fileName = Dir("C:\*.txt")
Dim arNames() As String
Dim myCount As Integer
myCount = -1
Do Until fileName = ""
myCount = myCount + 1
ReDim Preserve arNames(myCount)
arNames(myCount) = fileName
fileName = Dir
Loop
' Finish reading file names into arNames.
' This part of the code is successful
Dim TextArray()
Dim x As Double
Dim k As Integer
Dim UBound_arNames As Integer
UBound_arNames = UBound(arNames())
ReDim TotalArray(0 To 1000, 0 To UBound_arNames)
For k = 0 To 2
Open "C:\" & arNames(k) For Input As #1
' Open file.
Do While Not EOF(1) ' Loop until end of file.
ReDim Preserve TextArray(x) ' Preserve the Array
Line Input #1, TextArray(x) ' Read line into variable.
TotalArray(x, k) = TextArray(x)
' The bug is the above line. TextArray(x) works fine but it cannot be
' written to TotalArray(x, k). I need the second dimension k to make
' the second dimension contains the number of text files that I have
' I know the bug is here because MsgBox TextArray(0) works
' but MsgBox TotalArray(0,0) or any other cell prints nothing
x = x + 1 ' increment array count
Loop
Close #1 ' Close file.
MsgBox TextArray(0)
MsgBox TextArray(1)
Next k
End Sub
Please help me
You may be overthinking this and you may be using the wrong tool. This can easily be done with Power Query. Put all files into one folder. Get Power Query to read and append all files. Doesn't matter how many there are in the folder.
In Power Query you can just click through this with ribbon commands. You won't need to write code (although you can get creative with M if you want to). Data > Get Data > From File > From Folder. Take it from there.
When the data in the files changes, or when there are more or fewer files in the folder, just refresh the query.

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

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'

text to columns: split at the first number in the value

I have 1 column with about 60 cells with values or different length. Each (or at least most) of the values have a numeric characters in the value. I want to split the columns cells into more columns which I normally would do with the 'tekst to columns' function of excel.
But this function does not have an advanced option of splitting the value at the first numeric character. splitting based on spaces, comma etc. is possible but this does not help me.
Is there any way to divide the cells into 2 columns at the first number in the cell value?
I have looked at numerous other questions but none of them (or other internet fora) have helped me to split the value at the first number of the cell value.
Thanks #quantum285 for the answer. This routine works if the string contains one number. I changed the teststring to firstpart323secondpart.
then part1 returns 'firstpart32' and part2 return secondpart.
I tried to understand what happens in this code, please correct me if I'm wrong:
First, the lenght of the string is determined.
Secondly, for each position in this string is checked if it is numeric or not. But this check is dan from right to left? So in case of firstpart323secondpart: the length is 22.
then isnumeric() checks for every position from 1 to 22 if it is numeric and stops when it finds a number?
If so, part 1 is the the tekst before the value i, where i is the first position from right to left in the string where a number is found.
and part 2 is then the string on the right from this same position.
However, I am looking for a routine which find the first position from left to right (or the last position from right to left) where a number is, ...
So I changed the routine now, simply adjusting the for i = 1 to line:
Sub test()
For j = 4 To Cells(Rows.Count, 4).End(xlUp).Row
For i = Len(Cells(j, 4)) To 1 Step -1
If IsNumeric(Mid(Cells(j, 4), i, 1)) Then
Cells(j, 5) = Left(Cells(j, 4), i - 1)
Cells(j, 6) = (Right(Cells(j, 4), Len(Cells(j, 4)) - i + 1))
End If
Next i
Next j
End Sub
this almost perfectly works (except for a few cells which have multiple number combinations in the value (like: soup 10g 20boxes). But as these are only a few, I can adjust them by hand.
Thanks!
Sub test()
testString = "firstpart3secondpart"
For i = 1 To Len(testString)
If IsNumeric(Mid(testString, i, 1)) Then
part1 = Left(testString, i - 1)
part2 = (Right(testString, Len(testString) - i))
End If
Next i
MsgBox (part1)
MsgBox (part2)
End Sub
Use something like this within your loop.

Importing Tab Delimited Text File with Multiline Cells (to Excel or Access)

The tab delimited text file that i am trying to import looks like this (4 fields, Field 3 is multiline)... and about 100,000 rows of data:
Below is just a sample... but please give a general solution where the multiline text could be in multiple fields... like say fld3, fld6 and fld7 of a total 10 fields.
Field 1 <tab> Field 2 <tab> Field 3.1
Field 3.2
Field 3.3<tab>Field 4
Field 1 <tab> Field 2 <tab> Field 3.1
Field 3.2
Field 3.3<tab>Field 4
Field 1 <tab> Field 2 <tab> Field 3.1
Field 3.2
Field 3.3<tab>Field 4
But, actually when it was was exported to the above text file from the database... it had 3 lines of actual... that looked like this... 4 Fields. Field 3 is multiline.
Field 1 <tab> Field 2 <tab> Field 3.1(CR)Field 3.2(CR)Field 3.3<tab>Field 4
Field 1 <tab> Field 2 <tab> Field 3.1(CR)Field 3.2(CR)Field 3.3<tab>Field 4
Field 1 <tab> Field 2 <tab> Field 3.1(CR)Field 3.2(CR)Field 3.3<tab>Field 4
where is Tab, and (CR) is carriage return. When importing the tab delimited text file into Excel, i want all 3 lines in Field 3 (Field 3.1, Field 3.2 and Field 3.3) be in one cell, but multiline. So basically i want excel to ignore carriage return with in Field 3. How do i do that???
For your info... The text fields are NOT in double quotes... Please tell me what is the best way to convert the plain text tab delimited text file to Excel 4 columns like this:
does anyone know of a solution. it would be greatly appreciated.
Additional Comment
Please note that what I have is only the resulting Text File... as shown on the very top of this message.... with text "Field 3.2" in Line 2, "Field 3.3" and "Field 4" in Line 3 with separating them.
Also... not necessarily Field 3 will be always multiline... it may be multiline with 2, 3 or more lines... or even nothing or single line. Field 3 will never have a with in itself.
Additional Comments with Sample File for someone to Test - Update 25Jun2013 09:05 UTC
pls note copy paste will not work.. as tabs are lost.. you will have to add it yourselves.
File with Quotes around the multiline field:
f1hdr f2hdr f3hdr
f11 "f12
part of f12" f13
f21 "f22part of f22
part f22
part f22
part f22" f23
f31 "f32aaa" f33
f41 "f42bbb" f43
File without Quotes around the multiline field:
f1hdr f2hdr f3hdr
f11 f12
part of f12 f13
f21 f22part of f22
part f22
part f22
part f22 f23
f31 f32aaa f33
f41 f42bbb f43
Open the file with quotes in Excel... Open File Dialog... Hold Shift... and Click Open.. show the file nicely with multiline.
But opening the file without quotes.. doesn't work.. it breaks.
I have no idea why holding shift works. I knew of this from here: Import multiline csv files into Excel internationally
Now.. it still remains to be answered...
1) How to add the quotes around the text file in easier fashion before importing to Excel... Why Shift Open works? What if I want to control each delimited columns using text import wizard?
2) How to add the quotes around the fields by default in SQL Server 2015. This is in addition to above Q1. We still need a solution where we can't export the file again. But, for any new export.. someone could user the answer from Q2.
3) Any other methods which may be even simpler?
Here's what I came up with. If you can guarantee the last column will never have a carriage return, then this should work ok.
What this does is read the text file in VBA and brings it into the workbook. You have to specify how many fields to expect (in the test scenario, 4). This is so it can keep track of when it's ready to start a new row.
It's a little confusing because of the carriage returns, but step through the code and I think you'll be able to figure it out. Let me know if you have any questions.
Option Explicit
Const fieldCount = 4
Sub import()
Application.ScreenUpdating = False
Dim fileNumber As Integer
Dim data As String
Dim curCol As Long, curRow As Long
Dim dataCols As Long
Dim i As Long
Dim sh As Excel.Worksheet
Dim arr() As String
Dim hasCarriageReturn As Boolean
fileNumber = FreeFile()
Open "C:\test.txt" For Input As #fileNumber
curCol = 1
curRow = 1
Set sh = ThisWorkbook.Worksheets("Sheet1")
While Not EOF(fileNumber)
' if we reached the "correct" last column, then move to next row
If (curCol > fieldCount) Then
curCol = 1
curRow = curRow + 1
hasCarriageReturn = False
End If
Line Input #fileNumber, data
arr = Split(data, vbTab)
dataCols = UBound(arr)
If (dataCols = fieldCount - 1) Then
' full row has no carriage returns
hasCarriageReturn = False
For i = 0 To dataCols
sh.Cells(curRow, curCol).Value = arr(i)
curCol = curCol + 1
Next
ElseIf (dataCols = 0 And hasCarriageReturn = True) Then
' if there is only 1 value in the row, append it to the current column
sh.Cells(curRow, curCol - 1).Formula = sh.Cells(curRow, curCol - 1).Formula & Chr(10) & arr(0)
ElseIf (dataCols = 0 And hasCarriageReturn = False) Then
' carriage return begins in the first field
sh.Cells(curRow, curCol).Formula = sh.Cells(curRow, curCol).Formula & Chr(10) & arr(0)
curCol = curCol + 1
hasCarriageReturn = True
ElseIf (hasCarriageReturn) Then
' append first item to field 3, then rest goes in other columns
sh.Cells(curRow, curCol - 1).Formula = sh.Cells(curRow, curCol - 1).Formula & Chr(10) & arr(0)
For i = 1 To dataCols
sh.Cells(curRow, curCol).Value = arr(i)
curCol = curCol + 1
Next
hasCarriageReturn = False
Else
' process row and note that it has carriage returns
For i = 0 To dataCols
sh.Cells(curRow, curCol).Value = arr(i)
curCol = curCol + 1
Next
hasCarriageReturn = True
End If
Wend
Application.ScreenUpdating = True
End Sub
for the time being what i did was.. used gvim (same like 'vi') and replaced all
\t with "\t" (this is to have the fields wrapped in quotes...then.. e.g. :%s/\t/"\t"/g
\r\n with "\r (this is to have the real end of line to have a quote in the end... then e.g. :%s/\r\n/"\r/g
line start ^20 with ^"20 (this is for beginning of line first field in quotes... the line starts with 2013... so replacing with with "2013...) e.g. :%s/^2013/"2013/g
saved the file.. as file.txt
Open Excel
Select the File... and hold shift and click "open" (courtesy of: Import multiline csv files into Excel internationally)
All fields are nicely imported (in General Format) and multilines are processed correctly and put in correct fields.
This is truly wonderful... However with 1 caveat.
Some of the fields are text but with leading 0s.. e.g. '000327511' or '032'.. and i wanted the leading zero intact.. without excel converting to number. I can't preserve the leading 0 using the "shift + open" method.
If I use the normal text import wizard... then the multiline cannot be made to work.. catch 22 situation. Pity!!!
However.. this is a nice temporary solution until someone can find a permanent fix all one.
No code involved at all... just a few typing to replace with vi and click.. click..
Wish someone can improve this method slightly.
Import to Libre Office Calc. Libre Office Calc does not interpret line breaks in between two tabs as a next row command. The content after line break will appear in the next line within the same cell. Save the spreadsheet as ms excel xls/xlsx format.
Ignore the warning that pops up before it is saved at your own risk and/or proof-read the same spreadsheet after import. During the proof read make sure you're using Excel.

Resources