VBA create CSV with varying row lenght - vba

i am very new to VBA or programmin in general.
Nevertheless, I need to create a code for exporting a csv file.
My issue is that I have several rows with varying lenght in my file.
The file looks as following:
3,6,8
3,9,4,7,8
1
2,4
7,9,4,5,6,8,1
3
My codes gives me:
"3","6","8","","","",""
"3","9","4","7","8","",""
"1","","","","","",""
"2","4","","","","",""
"7","9","4","5","6","8","1"
"3","","","","","",""
I need:
"3","6","8"
"3","9","4","7","8"
"1"
"2","4"
"7","9","4","5","6","8","1"
"3"
Can anyone please help me?
Sub CIF_Katalog_2()
Dim i As Long, lngZeile As Long
Dim myCSVFileName As String
Dim myWB As Workbook
Set myWB = ThisWorkbook
myCSVFileName = myWB.Path & "\" & "CSV Katalog Export_" & VBA.Format(VBA.Now, "dd-MMM-yyyy hh-mm") & ".csv"
lngZeile = Range("A" & Rows.Count).End(xlUp).Row
Open myCSVFileName For Output As #1
For i = 1 To lngZeile
If i = 1 Then
Print #1, Chr(34) & Cells(i, 1).Value & Chr(34)
ElseIf i = 2 Then
Print #1, Chr(34) & Cells(i, 1).Value & Chr(34) & "," & Chr(34) & Cells(i, 2).Value & Chr(34)
Else
Print #1, Chr(34) & Cells(i, 1).Value & Chr(34) & "," & Chr(34) & Cells(i, 2).Value & Chr(34) & "," & Chr(34) & Cells(i, 3).Value & Chr(34) & "," & Chr(34) & Cells(i, 4).Value & Chr(34) & "," & Chr(34) & Cells(i, 5).Value & Chr(34) & "," & Chr(34) & Cells(i, 6).Value & Chr(34) & "," & Chr(34) & Cells(i, 7).Value & Chr(34) & "," & Chr(34) & Cells(i, 8).Value & Chr(34) & "," & Chr(34) & Cells(i, 9).Value & Chr(34) & "," & Chr(34) & Cells(i, 10).Value & Chr(34) & "," & Chr(34) & Cells(i, 11).Value & Chr(34) & "," & Chr(34) & Cells(i, 12).Value & Chr(34) & "," & Chr(34) & Cells(i, 13).Value _
& Chr(34) & "," & Chr(34) & Cells(i, 14).Value & Chr(34) & "," & Chr(34) & Cells(i, 15).Value & Chr(34) & "," & Chr(34) & Cells(i, 16).Value & Chr(34) & "," & Chr(34) & Cells(i, 17).Value & Chr(34) & "," & Chr(34) & Cells(i, 18).Value & Chr(34) & "," & Chr(34) & Cells(i, 19).Value & Chr(34) & "," & Chr(34) & Cells(i, 20).Value & Chr(34) & _
"," & Chr(34) & Cells(i, 21).Value & Chr(34) & "," & Chr(34) & Cells(i, 22).Value & Chr(34) & "," & Chr(34) & Cells(i, 23).Value & Chr(34) & "," & Cells(i, 24).Value & Chr(34) & "," & Chr(34) & Cells(i, 25).Value & Chr(34) & "," & Chr(34) & Cells(i, 26).Value & Chr(34) & "," & Chr(34) & Cells(i, 27).Value & Chr(34) & "," & Chr(34) & Cells(i, 28).Value & Chr(34) & "," & Chr(34) & Cells(i, 29).Value & Chr(34) & "," & Cells(i, 30).Value & "," & Chr(34) & Cells(i, 31).Value & Chr(34) & "," & Chr(34) & Cells(i, 32).Value & Chr(34) & "," & Chr(34) & Cells(i, 33).Value & Chr(34) & "," & Chr(34) & Cells(i, 34).Value & Chr(34) & "," & Chr(34) & Cells(i, 35).Value & Chr(34)
End If
Next i
Close #1
MsgBox "Erledigt"
End Sub

Give this a try... just reusing your code:
Sub CIF_Katalog_2()
Dim i As Long, x As Long, lngZeile As Long
Dim myCSVFileName As String, strTemp As String
Dim myWB As Workbook: Set myWB = ThisWorkbook
myCSVFileName = myWB.Path & "\" & "CSV Katalog Export_" & VBA.Format(VBA.Now, "dd-MMM-yyyy hh-mm") & ".csv"
lngZeile = Range("A" & Rows.Count).End(xlUp).Row
Open myCSVFileName For Output As #1
For i = 1 To lngZeile
For x = 1 To 35
If Cells(i, x) <> "" Then
strTemp = strTemp & Chr(34) & Cells(i, x).Value & Chr(34) & ","
End If
Next x
Print #1, Left(strTemp, Len(strTemp) - 1)
strTemp = ""
Next i
Close #1
MsgBox "Erledigt"
End Sub

Related

VBA Access Syntax Error in Insert Into Statement

strSQL = "INSERT INTO tbl_Processor_Info ([Division],[Service_Area],[Service_Line],[Service_Line_Process],[SLA_Type],[SLA_Ref],[Processing_Date],[Total_Processed],[Onshore_Error],[Invalid_Queries],[TAT_Missed],[RFT_Error],[Techinician]) VALUES('" & _
.Range("M" & i) & "','" & .Range("I" & i) & "','" & .Range("J" & i) & "','" & .Range("K" & i) & "','" & .Range("N" & i) & "','" & .Range("B" & i) & "',#" & .Range("A" & i) & "#," & .Range("C" & i) & "," & .Range("E" & i) & "," & .Range("F" & i) & "," & .Range("G" & i) & "," & .Range("H" & i) & ",'" & Environ("Username") & "')"
results in:
INSERT INTO tbl_Processor_Info ([Division],[Service_Area],[Service_Line],[Service_Line_Process],[SLA_Type],[SLA_Ref],[Processing_Date],[Total_Processed],[Onshore_Error],[Invalid_Queries],[TAT_Missed],[RFT_Error],[Techinician]) VALUES('ATA','PUT','DE','PBR','','SP-154',#02/01/2020#,4,,,1,,'arathod')

How to extract specific multiple text in SQL?

I am trying to extract specific text from 1 column which seems to have concatenated several data points. Here is an example of part of the output that appears in 1 row:
[{"q":{"as":[{"id":"1","tags":[{"tagid":"62","tagstr":"Example1"},{"tagid":"3","tagstr":"Example1"},{"tagid":"65","tagstr":"Example1"},{"tagid":"71","tagstr":"Example1"}],"text":"Example1"}],"hidden":"false","id":"1","questionalias":"1","text":"Example1","ttl":"Example1"}},
The text in bold is what I am trying to extract. In practice each 'Example1' is selected from an option of words. Therefore I know exactly what text I am looking for. What I am struggling with is creating a way for the output to strip out the unwanted text and return the key words (around 8)
Alternatively, if someone has done something similar in VBA, that could also be an option.
Has anyone faced this before?
You can parse you data with Regex! It's marvelous!
There're plenty (Left, Mid, Right, Instr) functions to parse your data, right?
Some people, when confronted with a problem, think
“I know, I'll use regular expressions.”
Now they have two problems.
I think, that you trying to bound to some keywords(tagstr, text and ttl), so take a look at this.
Feel free to modify this expression, take a look on this and that!
In VBA there's no regex from scratch , so add VBA reference to "Microsoft VBScript Regular Expressions 5.5"
This is my exapmle with your data:
Sub test()
Dim Data As String
Dim Re As RegExp
Dim ReMatch As MatchCollection
Dim CurrentMatch As Match
Data = "[{" & Chr(34) & "q" & Chr(34) & ":{" & Chr(34) & "as" & Chr(34) & ":[{" & Chr(34) & "id" & Chr(34) & ":" & Chr(34) & "1" & Chr(34) & "," & Chr(34) & "tags" & Chr(34) & _
":[{" & Chr(34) & "tagid" & Chr(34) & ":" & Chr(34) & "62" & Chr(34) & "," & Chr(34) & "tagstr" & Chr(34) & ":" & Chr(34) & "Example1" & Chr(34) & "},{" & Chr(34) & "tagid" & Chr(34) & ":" & Chr(34) & "3" & Chr(34) & _
"," & Chr(34) & "tagstr" & Chr(34) & ":" & Chr(34) & "Example1" & Chr(34) & "},{" & Chr(34) & "tagid" & Chr(34) & ":" & Chr(34) & "65" & Chr(34) & "," & Chr(34) & "tagstr" & Chr(34) & ":" & Chr(34) & "Example1" & Chr(34) & _
"},{" & Chr(34) & "tagid" & Chr(34) & ":" & Chr(34) & "71" & Chr(34) & "," & Chr(34) & "tagstr" & Chr(34) & ":" & Chr(34) & "Example1" & Chr(34) & "}]," & Chr(34) & "text" & Chr(34) & ":" & Chr(34) & "Example1" & Chr(34) & _
"}]," & Chr(34) & "hidden" & Chr(34) & ":" & Chr(34) & "false" & Chr(34) & "," & Chr(34) & "id" & Chr(34) & ":" & Chr(34) & "1" & Chr(34) & "," & Chr(34) & "questionalias" & Chr(34) & ":" & Chr(34) & "1" & Chr(34) & _
"," & Chr(34) & "text" & Chr(34) & ":" & Chr(34) & "Example1" & Chr(34) & "," & Chr(34) & "ttl" & Chr(34) & ":" & Chr(34) & "Example1" & Chr(34) & "}},"
Debug.Print "My data is:" & vbNewLine & Data
Set Re = New RegExp
Re.IgnoreCase = True
Re.Global = True
Re.MultiLine = True
Re.Pattern = "(?=" & Chr(34) & "tagstr" & Chr(34) & "|" & Chr(34) & _
"text" & Chr(34) & "|" & Chr(34) & "ttl" & Chr(34) & ")(?:" & Chr(34) & _
"\w*" & Chr(34) & ":" & Chr(34) & "(.*?)" & Chr(34) & ")"
Debug.Print "My pattern is:" & vbNewLine & Re.Pattern
Set ReMatch = Re.Execute(Data)
Debug.Print "Matched " & ReMatch.Count & " times!"
For Each CurrentMatch In ReMatch
Debug.Print "Capture " & CurrentMatch.SubMatches(0) & " in " & CurrentMatch.Value
Next
End Sub
Output:
Not so complicated, right?
You can do this with standart string functions after all..

How to Implement Formula into Excel cells using VBA

I want to implement the following formula in to Excel cells
IF(OR(D12>0,C13=""),"",MAX(SUM($C$12:C13)-$D$9,0))
(once formula is applied I should get following result (formula implemented manually):
so i wrote simple macro as below , but unable to implement formula , formula retuns value as "true"
Sub adjustoldbills()
lastRow_sht4 = Sheet4.Range("A" & Rows.Count).End(xlUp).Row
Sheet4.Cells(12, 11) = ""
For i = 1 To lastRow_sht4 - 10
If Sheet4.Cells(11 + i, 1) <> "" Then
'=MAX(SUM($C$12:C15)-$D$9,0)
Sheet4.Cells(12, 4).Formula = "=MAX(SUM($C$12:C" & 12 & ")-$D$9,0)"
Sheet4.Cells(11 + i, 4).Formula = "=(if(or(D" & 11 + i > 0 & ",C" & 12 + i & "=" & Chr(34) & Chr(34) & ")," & Chr(34) & Chr(34) & "," & "MAX(SUM($C$12:C" & 12 & i & ")-$D$9,0)"
End If
Next i
End Sub
i am getting wrong result after implemented formula via vba macro as in this image:
how to implement formula and get value as expected.
When trying to convert long formulas to VBA try using a String variable to help you test it.
Dim FormulaStr As String
FormulaStr = "=IF(OR(D" & 11 + i & ">0,C" & 12 + i & "=" & Chr(34) & Chr(34) & ")," & _
Chr(34) & Chr(34) & ",MAX(SUM($C$12:C" & 12 + i & ")-$D$9,0))"
Debug.Print FormulaStr
Then, in the immediate window you will get:
=IF(OR(D12>0,C13=""),"",MAX(SUM($C$12:C13)-$D$9,0))
which is the formula you want to convert to VBA.
Now all you need to do is to add the line below:
Sheet4.Cells(11 + i, 4).Formula = FormulaStr
If you want to skip the String variable, you can just replace your line of
Sheet4.Cells(11 + i, 4).Formula = "=(if(or(D" & 11 + i > 0 & ",C" & 12 + i & "=" & Chr(34) & Chr(34) & ")," & Chr(34) & Chr(34) & "," & "MAX(SUM($C$12:C" & 12 & i & ")-$D$9,0)"
to:
Sheet4.Cells(11 + i, 4).Formula = "=IF(OR(D" & 11 + i & ">0,C" & 12 + i & "=" & Chr(34) & Chr(34) & ")," & Chr(34) & Chr(34) & ",MAX(SUM($C$12:C" & 12 + i & ")-$D$9,0))"
I'd go another way, with no loops and exploiting SpecialCells() method of Range object
Option Explicit
Sub adjustoldbills()
With Sheet4
.Range("D12").FormulaR1C1 = "=MAX(RC[-1]-R9C4,0)"
With .Range("A13", .Cells(.Rows.Count, 1).End(xlUp)).SpecialCells(xlCellTypeConstants)
With .Offset(, 2).SpecialCells(xlCellTypeConstants)
.Offset(, 1).FormulaR1C1 = "=IF(R[-1]C>0,"""",MAX(SUM(R12C[-1]:RC[-1])-R9C4,0))"
With .Areas(.Areas.Count)
.Offset(, 1).Cells(.Rows.Count).Offset(1).FormulaR1C1 = "=IF(R[-1]C>0,"""",MAX(SUM(R12C[-1]:RC[-1])-R9C4,0))"
End With
End With
End With
End With
End Sub

Syntax of Cells.offset.value

I have a few lines of code, and I don't know why they don't work.
Dim strValSumMonth As String
strValSumMonth = "=SUMIF(" & Cells(i, j).Resize(, 4).Address(False, False) & ";" & Chr(34) & "OK" & Chr(34) & ";" & Range(strAdresseOKpasOk).Resize(, 4).Address(False, False) & ")"
Cells(i, j).Offset(0, 5).Value = strValSumMonth
The value strValSUmMonth is for example "=SUMIF(Z3:AC3;"OK";Z34:AC34)"
The bug here is in the last code line.
Any help please ?

How to add an incremental count (version) to a string (file) in Excel/VBA?

I have tried a lot of different things, and it seems like I cannot get it to work. So basically, this is a small piece of my complete code.
I am using Microsoft Scripting Runtime to save the file, using the FileExists() to check if the file actually exist before saving.
This is working fine if I remove the IF-statement/Loop.
However, now it feels like FileExists won´t find the string, MyFilePath, when I run it with the IF/Loop. (getdirsubparentpath is a function)
Dim week, UserName As String
Dim MyFile, MyFilePath As String
Dim version As Integer
' Current week, XX
week = Format(Date, "ww")
' Username, e.g. niclas.madsen
UserName = Environ$("UserName")
' Initials, first letter of last and surname to caps
' e.g. niclas.madsen would be NM
UserName = UCase(Left(UserName, 1) & Mid(UserName, InStr(UserName, ".") + 1, 1))
' fix filename for saving purpose
MyFile = Replace(Replace("SupplierOrganization_W", "", ""), ".", "_") _
& "" _
& week _
& " " _
& UserName _
& ".csv"
'SupplierOrganization_WXX NM
MyFilePath = getDirSubParentPath & MyFile
' Look for the MyFilePath, if it exists then
' Add "-1" after the week number, if 1 exists, add 2, etc.
If Len(Dir(MyFilePath)) <> 0 Then
version = 0
Do
version = version + 1
MyFilePath = Dir(getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version & " " & UserName & ".csv")
Loop Until Len(Dir(MyFilePath)) < 0
End If
Dim tmpFile, tmpFilePath As String
tmpFile = getDirSubParentPath & "tmp_file.txt"
Dim tmpString As String
'Dim fso As New FileSystemObject
Dim fso As Object 'scripting.filesystemobject
Set fso = CreateObject("scripting.filesystemobject")
If fso.FileExists(MyFilePath) = True Then
Application.ScreenUpdating = False
Open MyFilePath For Input As #1
Open tmpFile For Output As #2
tmpString = Input(LOF(1), 1) 'read the entire file
tmpString = Replace(tmpString, (Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34)), "") 'eliminate double quotation and commas in the first line with UTF-8
Print #2, tmpString 'output result
Close #1
Close #2
fso.DeleteFile (MyFilePath) 'delete original file
fso.CopyFile tmpFile, MyFilePath, True 'rename temp file
fso.DeleteFile (tmpFile) 'delete temp file
Application.ScreenUpdating = True
MsgBox "Finished processing file", vbInformation, "Done!"
Else
MsgBox "Cannot locate the file : " & MyFilePath, vbCritical, "Error"
End If
Set fso = Nothing
End Sub
' Get Parent Sub Directory Path
Function getDirSubParentPath()
getDirSubParentPath = ThisWorkbook.Path & Application.PathSeparator & "CSV" & Application.PathSeparator & "Parent" & Application.PathSeparator
End Function
I finally manage to create a solution that seems viable. However, the code could use some cleaning up :) But it gets the job done.
So basically, I am having some issues with the loop. It will return a file named W16-0 (which should actual just be W16). It should only add the "-X" if W16 is found. So the incremental order should be W16, W16-1, W16-2, etc.
What I am doing is that I try to locate if there is a W16-0 and then replace it with W16. Furthermore, it seems like the loop will give me one higher than the amount of files I have. So that is where I also got an error. So if I had a W16-4, it would ask the macro to find and open a file named W16-5, which would obviously not exist.
If somebody could help me clean up the code, I would be really thankful!
Sub RemoveCommasDoubleQ()
'
' Enable a reference to 'Microsft Scripting Runtime'
' under VBA menu option Tools > References
Dim week, UserName As String
Dim MyFile, MyFilePath As String
Dim version As Integer
Dim fso As Object 'scripting.filesystemobject
Set fso = CreateObject("scripting.filesystemobject")
' Current week, XX
week = Format(Date, "ww")
' Username, e.g. niclas.madsen
UserName = Environ$("UserName")
' Initials, first letter of last and surname to caps
' e.g. niclas.madsen would be NM
UserName = UCase(Left(UserName, 1) & Mid(UserName, InStr(UserName, ".") + 1, 1))
' fix filename for saving purpose
MyFile = Replace(Replace("SupplierOrganization_W", "", ""), ".", "_") _
& "" _
& week _
& " " _
& UserName _
& ".csv"
'SupplierOrganization_WXX NM
'MyFilePath = ThisWorkbook.Path & "\CSV\Parent\" & MyFile
MyFilePath = getDirSubParentPath & MyFile
Debug.Print MyFilePath
Debug.Print "BEFORE LOOP"
'version = 1
Do While Len(Dir(MyFilePath)) <> 0
'// If it does, then append a _000 to the name
'// Change _000 to suit your requirement
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version & " " & UserName & ".csv"
'// Increment the counter
version = version + 1
'// and go around again
If MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-0" & " " & UserName & ".csv" Then
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & " " & UserName & ".csv"
Debug.Print MyFilePath
Debug.Print "IF LOOP"
End If
Loop
Debug.Print MyFilePath
Debug.Print "LOOP"
If fso.FileExists(getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version & " " & UserName & ".csv") = False Then
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version - 2 & " " & UserName & ".csv"
MsgBox getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version & " " & UserName & ".csv"
End If
fileName = fso.GetFileName(MyFilePath)
Debug.Print fileName
If MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-0" & " " & UserName & ".csv" Then
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & " " & UserName & ".csv"
Debug.Print MyFilePath
Debug.Print "her it should be 0"
End If
If MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-" & " " & UserName & ".csv" Then
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version & " " & UserName & ".csv"
End If
Debug.Print "HER ER VI"
fileName = fso.GetFileName(MyFilePath)
Debug.Print fileName
Dim tmpFile, tmpFilePath As String
tmpFile = getDirSubParentPath & "tmp_file.txt"
Dim tmpString As String
Debug.Print "------"
Debug.Print MyFilePath
If fso.FileExists(getDirSubParentPath & "SupplierOrganization_W" & week & "-0" & " " & UserName & ".csv") = True Then
MsgBox "Found the W-0"
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & " " & UserName & ".csv"
End If
Debug.Print "Found 0?"
Debug.Print MyFilePath
If fso.FileExists(MyFilePath) = True Then
Application.ScreenUpdating = False
Open MyFilePath For Input As #1
Open tmpFile For Output As #2
tmpString = Input(LOF(1), 1) 'read the entire file
tmpString = Replace(tmpString, (Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34)), "") 'eliminate double quotation and commas in the first line with UTF-8
Print #2, tmpString 'output result
Close #1
Close #2
fso.DeleteFile (MyFilePath) 'delete original file
fso.CopyFile tmpFile, MyFilePath, True 'rename temp file
fso.DeleteFile (tmpFile) 'delete temp file
Application.ScreenUpdating = True
MsgBox "Finished processing file", vbInformation, "Done!"
Else
MsgBox "Cannot locate the file : " & MyFile, vbCritical, "Error"
End If
Set fso = Nothing
End Sub