My customer has a file they have used, for some time, to upload data to their application. The field in the Oracle table is VARCHAR 50. The field in the Excel spreadsheet they use is column width 50 and marked as General. I change it to Text and save as .csv. All the rows that have alphanumeric in the field save fine, but the ones that are all numbers convert to scientific notation. I found something on here changing the format (Data > Text to columns) from General to Text. Nothing makes the numbers convert as text like the other values in the field in this spreadsheet. What can I do to ensure it does this every time? They say it is the 1st time they've seen it... I doubt that. Still, I am on the hook to solve the problem. I need to provide them with a solution so that when they send me this data, twice a year, to upload, it works correctly. Any help would be greatly appreciated. Thanx.
Public Sub WritetxtFiles()
Const DELIMITER As String = ","
Dim myRecord As Range
Dim myField As Range
Dim nFileNum As Long
Dim sOut As String
Dim counter As Long
Dim holder As String
Dim theDate As Date
Dim formattedDate As String
Dim dailyDirectory As String
nFileNum = FreeFile
theDate = Now
formattedDate = Format(theDate, "yyyyMMdd")
dailyDirectory = "C:\TEMP\" + formattedDate
If Dir(dailyDirectory, vbDirectory) = vbNullString Then
MkDir (dailyDirectory)
Else
End If
Sheets("orig.txt").Activate ' Adjust to match your sheet name
Open dailyDirectory & "\orig.txt" For Output As #nFileNum ' Adjust to match your desired output
counter = 1
For Each myRecord In Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row)
If Cells(counter, 1) <> "" Then
With myRecord
For Each myField In Range("A" & counter, "F" & counter)
sOut = sOut & DELIMITER & myField.Text
Next myField
Print #nFileNum, Mid(sOut, 2)
sOut = Empty
End With
Else
End If
counter = counter + 1
Next myRecord
Close #nFileNum
end sub
This will create a comma delimited file in your C:\Temp[yyyymmdd]
Well, this is for a gov't customer and they don't allow macros in their Excel files. I was able to save as a 97-2003 workbook, then save as .csv. If I open with Notepad instead of Excel, the .csv file appears correct. If I open it with Excel, it converts. Go figure. Thanx for the help. Wish I could have used it.
Related
I currently have a log file that get generated when you click on a button.
At the beginning of the .log you have a preview with different information such as the login, url of a server etc... But you also have the date of the beginning of the process and the date for the end. Both are in the long date format and are displayed correctly in the log file.
That log file takes the information from a sheet the preview part is static and is a range ("A1:C13") and the rest of the log is beneath but still in the columns ("A:C").
The cells in excel :
I want to add a line that shows the difference between the two date, to quickly see the time the process took.
However when I'm creating the log file, I get the time difference in number.
eg : in excel the cell with the format shows 00:01:55 but in the log file I get 0,001331
The output in the .log :
So far I tried :
To force the format in vba when the export in processing
To copy/paste in value with the hour format to not show the subtraction in the cell
different kind of format but it wasn't conclusive
You'll find the code that create the log file here :
Private Sub iExportLog(Optional LogPath As String, Optional bouton As String)
Dim NF As Integer, C As Range, posi As Integer
Dim date_nom As String
Dim drct As String
NF = FreeFile
drct = ThisWorkbook.path & "\_LogELB"
Set C = iFLog.Range("A1")
' iFLog = the sheet
' Things I tried :
'iFLog.Range("C12") = Format(iFLog.Range("C11").Value - iFLog.Range("C2").Value, "hh:mm:ss")
'iFLog.Range("C12").NumberFormat = "hh:mm:ss"
'
posi = InStrRev(ThisWorkbook.Name, ".")
If Dir(drct, vbDirectory) = "" Then MkDir (ThisWorkbook.path & "\" & "_LogElb")
date_nom = Format(CStr(Now), "yyyy_mm_dd_hh_mm_ss_")
If LogPath = "" Then LogPath = drct & "\" & bouton & "_" & date_nom & ".log"
Open LogPath For Append As #NF
Do While C.Value <> ""
Print #NF, C.Value & vbTab & vbTab & vbTab & C.Offset(0, 1).Value & vbTab & C.Offset(0, 2).Value
Set C = C.Offset(1, 0)
Loop
Close #NF
End Sub
I don't have a lot of practice with manipulating dates but I know that it can be painful.
Is there a way to display a date subtraction correctly when generating a .log/.txt file ?
If you write a formatted time string to a cell then Excel will interpret that as a time value and "undo" your formatting, converting the value back to a numeric value (though the display format may hide that).
If you want to keep the "hh:mm:ss" format then first set the cell format to "Text", or prepend the string with ' before placing it in the cell. Or read the cell's Text property instead of Value
i need to separate the columns of my dataset into comma separated how con I do this? I need a dataset that looks like this:
#VBasic2008 here is what i get in the middle of the sheet: the first and second row are my tries with your function CONCAT. While i need something like the rightest part of the image.... like 6,40,45,52. Not all the values merged..
So i did it using CONCAT function but i had to manually compute that for each column i show how for the ones that eventually will need help (note i used ; instead of , beacause my excel seems not working with ,)
and this is finally the final output
Ok but what if I have a dataset of 1000 columns? This process need to be much much quicker than this. This is not optimized.
I have written several comments on your question which may be hard to follow. So I decided to make a full solution which actually a trick.
Note that Microsoft Excel tries to guess the data structure of the file content if the file is suffixed with .csv (extension). For that reason, whenever you open a .csv file, you get your data in columns instead of a single columns with comma separated values.
In order to achieve what you want, first, save your data as in the comma separated values (.csv) file format.
Then change your file extension from .csv to, i.e. .txt (text file) for example:
if your file name is "data.csv", change it to "data.txt". Please make sure you see the file extension as csv before you change it because in some case you don't see the file extension; therefore when you rename it, it remains a csv file.
Note: If you don't see file extension, if you are on Microsoft Windows, follow this link.
Once you rename the file into txt file format, you can then open it in your Excel application by going to File -> Open -> then browse the txt file.
There you go and get what you one.
You don't need to code or use any functions to achieve that although you can choose to do so if you wish as it is also a good solution.
If you are looking for a formula solution
TEXTJOIN(", ", TRUE, Range)
where Range is the column span of expected values
Option Explicit
Sub CSV()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim LR As Long, xRow As Range
LR = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
Application.ScreenUpdating = False
For Each xRow In ws.Range("A1:A" & LR)
xRow.Offset(0, 6).Value = WorksheetFunction.TextJoin(", ", True, xRow.Resize(1, 6))
Next xRow
Application.ScreenUpdating = True
End Sub
This is already separated by commas, so you just have to rename it to a .csv file.
in Windows Explorer, go to the ribbon and go to the 'view' tab and enable 'File Name Extensions'.
Navigate to your file, right click and rename it to THEFILENAME.csv instead of THEFILENAME.xlsx
Now when you open this up in excel, it should have the grid.
What is the extension of the file? .xls, .txt or .csv?
If it is in .xls then you can simply open the file in Excel and then use the File->save as menu and then selecting the Comma Separated from the file type drop down.
If file has .csv extension and you are trying to open it in Excel then you will see columns even the file has commas in it. To verify that if the file is comma separated then simply open with notepad or other text editors to see the comma separated values.
If there is any other separator like colon : or other and want to replace with comma then simply use the find and replace option in notepad.
CONCAT Excel UDF
I wrote this a while ago.
In VBE add a module and copy the following code to it.
The Code
'*******************************************************************************
' Purpose: Concatenates the values of cells of a specified range.
' Read only. String.
' Syntax: CONCAT(Range, Separator, Row0Column1)
' Inputs:
' Range A valid range in any open workbook. Required.
' Separator A string to be used as a separator between the values.
' Default is the space character. Optional.
' Row0Column1 If 0 it concatenates by row, if 1 then by column.
' Default is 0. Optional.
' Returns: A string containing all the values of the specified range.
'*******************************************************************************
Function CONCAT(ByVal Range As Range, Optional Separator As String = _
" ", Optional Row0Column1 As Long = 0) As String
'***************************************
' Variables
Dim xdRowStart As Long, xdRowEnd As Long, xdRowCounter As Long
Dim xdColumnStart As Long, xdColumnEnd As Long, _
xdColumnCounter As Long
Dim xdSep As String, xdString As String, xdCheckEmptyString As String
Dim xdWS As Worksheet
'***************************************
' Values
xdString = ""
xdSep = Separator
Set xdWS = Range.Worksheet
xdRowStart = Range.Row
xdRowEnd = xdRowStart + Range.Rows.count - 1
xdColumnStart = Range.Column
xdColumnEnd = xdColumnStart + Range.Columns.count - 1
'***************************************
' Determine concatenated direction: by row or by column
Select Case Row0Column1
Case 0
GoTo ConcatenateByRow
Case 1
GoTo ConcatenateByColumn
Case Else
MsgBox "Row0Column1:" & vbCr _
& "Ommit or use 0 for Concatenating by Row." & vbCr _
& "Use 1 for Concatenating by Column."
GoTo ConcatenateFinal
End Select
'***************************************
' Concatenate by Row:
ConcatenateByRow:
For xdRowCounter = xdRowStart To xdRowEnd
For xdColumnCounter = xdColumnStart To xdColumnEnd
If xdString = "" Then 'xdString is empty; all cells were empty so far
xdCheckEmptyString = xdWS.Cells(xdRowCounter, xdColumnCounter)
If xdCheckEmptyString <> "" Then 'Cell is not empty
xdString = xdCheckEmptyString
End If
Else 'xdString is not empty
xdCheckEmptyString = xdWS.Cells(xdRowCounter, xdColumnCounter)
If xdCheckEmptyString <> "" Then 'Cell is not empty
xdString = xdString & xdSep & xdCheckEmptyString
End If
End If
Next xdColumnCounter
Next xdRowCounter
GoTo ConcatenateFinal
'***************************************
' Concatenate by Column:
ConcatenateByColumn:
For xdColumnCounter = xdColumnStart To xdColumnEnd
For xdRowCounter = xdRowStart To xdRowEnd
If xdString = "" Then 'xdString is empty; all cells were empty so far
xdCheckEmptyString = xdWS.Cells(xdRowCounter, xdColumnCounter)
If xdCheckEmptyString <> "" Then 'Cell is not empty
xdString = xdCheckEmptyString
End If
Else 'xdString is not empty
xdCheckEmptyString = xdWS.Cells(xdRowCounter, xdColumnCounter)
If xdCheckEmptyString <> "" Then 'Cell is not empty
xdString = xdString & xdSep & xdCheckEmptyString
End If
End If
Next xdRowCounter
Next xdColumnCounter
GoTo ConcatenateFinal
'***************************************
ConcatenateFinal:
CONCAT = xdString
End Function
'*******************************************************************************
Usage in Excel
=CONCAT($A1:$G1,",") and copy down:
=CONCAT($A2:$G2,",")
I'm using this code from here to Transposed convert excel to csv file. It's working perfect (Thanks to Nat).
Now I'm facing an issue : as I want to read from this file to fill out Autocad table, I need to csv number format to be as "Text" format(now it's "General" format which is normally happening when it opens with excel). When I import my csv data, it omits leading zero cells and changing 1:100 to 0.01.
When I open csv file with excel and change those cells format to "Text", then save and close file, it's working fine. How can I automate this process (or save with Text format in the first place) as I don't want each user do this manually.
Thanks
Private Sub Exporttocsv()
Dim ColNum As Integer
Dim Line As String
Dim LineValues() As Variant
Dim OutputFileNum As Integer
Dim PathName As String
Dim RowNum As Integer
Dim SheetValues() As Variant
PathName = Application.ActiveWorkbook.Path
OutputFileNum = FreeFile
Open PathName & "\Test.csv" For Output Lock Write As #OutputFileNum
SheetValues = Sheets("Current Revision").Range("B2:CV98").value
Dim RowMax
RowMax = UBound(SheetValues)
Dim ColMax
ColMax = 99
ReDim LineValues(1 To RowMax)
For ColNum = 1 To ColMax
For RowNum = 1 To RowMax
LineValues(RowNum) = SheetValues(RowNum, ColNum)
Next
Line = Join(LineValues, ",")
Print #OutputFileNum, Line
Next
Close OutputFileNum
End Sub
Verify that the CSV contains the values as you want them (e.g. 1:100 instead of 0.01), using any text viewer/editor like notepad, etc.
If values aren't formatted correctly, then to format them as text:
With Sheets("Current Revision").Range("B2:CV98")
.numberformat = "#"
.entirecolumn.autofit 'To avoid #### errors as we're using text property below
SheetValues = .text
End with
The above should replace this line in your original code.
SheetValues = Sheets("Current Revision").Range("B2:CV98").value
The alternative would be to modify the values in the array to, before printing to text file.
Untested and written on mobile, sorry for bad formatting. Hope it works.
For writing the 1:100 ratio as is, into CSV, best is to use the type conversion when you are writing values in to the CSV file. like below :
LineValues(RowNum) = CStr(SheetValues(RowNum, ColNum))
However, if you want leading Zeros, i dont think the type conversion also retains the leading zeros.
I'm currently comparing 2 databases where ZIP codes have been entered manually. I need to compare the ZIP codes for hundreds of accounts in each database to check if anything is missing. I've ordered all the values in ascending order in excel but cant seem to find a quick way to check what's missing.
Column A: Database A ZIPS (The correct ZIPs)
14464, 14515, 14612, 14615, 14626
Column B: Database B ZIPS (Manually Entered)
14464, 14612, 14615, 14626
Column C: Missing ZIPs
14515
EDIT: I should have clarified, the data is stored in this manner.. each zip is not stored in a separate column, there are multiple Zips for each agent.
Image of worksheet
I know there must be a way to find this value using an excel VBA!
Thanks
Answer prior to seeing author's data format
Luckily the task is not too hard. You just need to simply use:
=IF(COUNTIF(list,value),"Output if it exists","Output if missing")
So in your case using the columns you define...
=IF(COUNTIF($B:$B,$A1),"",A1)
Then apply the formula for the length of the correct zip column.
see: https://exceljet.net/formula/find-missing-values
Example picture here
give this a go
Public Function ShowMissingZips(rngSource As Range, _
rngMatch As Range) As String
Dim colSource As Collection
Dim colMatch As Collection
Dim colOutput As Collection
Dim varSource As Variant
Dim varMatch As Variant
Dim varOutput As Variant
Dim intCounter As Integer
Dim blnMatched As Boolean
Dim strSource As String
Dim strMatch As String
Dim strOutput As String
Set colSource = New Collection
Set colMatch = New Collection
Set colOutput = New Collection
strSource = Replace(rngSource.Value, " ", "")
For Each varSource In Split(strSource, ",")
colSource.Add varSource
Next
' Clean up source data
strMatch = Replace(rngMatch.Value, " ", "")
For Each varSource In Split(strMatch, ",")
colMatch.Add varSource
Next
' Clean up match data
For Each varSource In colSource
blnMatched = False
For Each varMatch In colMatch
If varSource = varMatch Then
blnMatched = True
Exit For
End If
Next
' Note if it's not matched
If Not blnMatched Then
colOutput.Add varSource
End If
Next
' Only output if there's anything present
If colOutput.Count > 0 Then
For Each varOutput In colOutput
strOutput = strOutput & CStr(varOutput) & ", "
Next
strOutput = Left$(strOutput, Len(strOutput) - 2)
End If
ShowMissingZips = strOutput
End Function
To use it, press Alt-F11 to get to the VBA editor. Find your workbook in the project explorer (Ctrl-R if not visible) and on the menu at the top click Insert..., Module.
Paste this code in.
Go back to your workbook and assuming that you've kept the columns as before (A, B & C and with row 2 as the first data row), go to cell C2 and type
=ShowMissingZips(A2,B2)
You should see what you're after. It's not pretty and I'd normally add error handling, but it'll do for a quick fix.
When you save it, be sure to use the XLSM format (Excel 2007+) so that the VBA is retained.
I am working on a project that requires non technical people to edit an excel file.
The file contains 2 columns, one is a key and one is a value. The key is an integer and the value is html. I need a text file to be generated by a non technical person that takes the form:
|[key][ tab \t][value]
|[key][ tab \t][value]
|[key][ tab \t][value]
The | is needed because the html could be multiline.
Any help is appreciated.
It sounds like you'll need a dab of VBA to get it working. This should get you started.
Sub writeKeysValues()
Dim i As Integer
Dim outFile As String
Dim fNum1 As Integer
'Open file
outFile = "C:\temp\outfile.txt"
fNum1 = FreeFile()
Open outFile For Output As fNum1
'loop through non-blanks
i = 1
With Worksheets("Book1")
Do Until .Cells(i, 1).Value = ""
Print #fNum1, "|" & .Cells(i, 1).Value & vbTab & .Cells(i, 2).Value
i = i + 1
Loop
End With
'All done
Close #fNum1
End Sub
Notes:
You will have to save the file as an Excel-macro-enabled spreadsheet (.xlsm).
It will stop reading at a blank key.
Writing is hardcoded to the C:\temp\outfile.txt.
This will win no code design contests, but it should give you an idea of how to write it out with the pipes and tabs exactly as you desire.