Automate report making VBA - excel

I'm trying to automate a report making, i have to copy/paste data from .txt files that are in the same carpet, to do so i use a window because using the path is inefficient when using in other computers. Errors i encounter:
I want the data type of all the cells to be text so i can transform
the date into dd/mm/yyyy
It only modifies some files and some not.
I've tried tons of macros i've made but i can't fix the errors.
Sub REP_DET_Report()
myBook = ActiveWorkbook.Name
Set nav = CreateObject("shell.application")
folder = nav.browseforfolder(0, "PICK FOLDER", 0, "c:\").items.Item.Path
ChDir folder & "\"
file = Dir("*.txt")
Do While file <> ""
Workbooks.OpenText file, origin:=xlWindows, startrow:=1, DataType:=xlDelimited
Dim objRange1 As Range
'Set up the ranges
Set objRange1 = Range("A1:A1048576")
'Do the first parse
objRange1.TextToColumns _
Destination:=Range("A1"), _
FieldInfo:=Array(Array(1, xlTextFormat), Array(2, xlTextFormat), Array(3, xlTextFormat), Array(4, xlTextFormat), Array(5, xlTextFormat), Array(6, xlTextFormat), Array(7, xlTextFormat), Array(8, xlTextFormat), Array(9, xlTextFormat), Array(10, xlTextFormat)), _
DataType:=xlDelimited, _
Tab:=False, _
Semicolon:=False, _
Comma:=False, _
Space:=False, _
other:=True, _
OtherChar:="|"
other = ActiveWorkbook.Name
ActiveSheet.Copy before:=Workbooks(myBook).Sheets(1)
Workbooks(other).Close False
file = Dir()
Loop
End Sub

Related

Edit this code that it can open ANY .dcm file and not the specific one i selected

I want to open .dcm files and edit them. Then the .dcm is read and placed before the active sheet i have on my current workbook. But i need to open any .dcm file, not only one specific one.
This is my current code
Sub Makro2()
'
' Makro2 Makro
'
'
Workbooks.OpenText Filename:= _
"H:\ENA\N_EN_AD3\3000_Mitarbeiter\Babacan\von_Nils\C7BB2HD3IINA_NRM_X302.dcm", _
Origin:=28592, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=True, Semicolon:=True, _
Comma:=True, Space:=True, Other:=False, FieldInfo:=Array(Array(1, 1), _
Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1)), TrailingMinusNumbers:=True
Range("A1").Select
Sheets("C7BB2HD3IINA_NRM_X302").Select
Sheets("C7BB2HD3IINA_NRM_X302").Move Before:=Workbooks( _
"ChrSet_Applikationsumgebung_inklHiAlti_X248_20221130.xlsm").Sheets(8)
End Sub
Usual method is to use a dialog box.
Option Explicit
Sub Makro2()
Const FOLDER = "H:\ENA\N_EN_AD3\3000_Mitarbeiter\Babacan\von_Nils\" ' initial search
' select file
Dim filename As String
With Application.FileDialog(msoFileDialogFilePicker)
.InitialFileName = FOLDER
.Title = "Please select the file to read"
.Filters.Add "DCM File", "*.dcm", 1
.Show
.AllowMultiSelect = False
If .SelectedItems.Count = 0 Then 'If no file is selected, abort
MsgBox "You did not select a file", vbExclamation
Exit Sub
End If
filename = .SelectedItems(1)
End With
' open selected workbook
Workbooks.OpenText filename:=filename, _
Origin:=28592, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=True, Semicolon:=True, _
Comma:=True, Space:=True, Other:=False, FieldInfo:=Array(Array(1, 1), _
Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1)), TrailingMinusNumbers:=True
With ActiveWorkbook
.Sheets(1).Move Before:=ThisWorkbook.Sheets(8)
End With
MsgBox "Done"
End Sub

VBA: How to keep blank cells when importing Text file data into Excel

I'd like to keep a cell with blank when there is no data.
Keep a cell with blank
I like to keep C3 as Empty cell like this Sample.
But My VBA gave me Sample.
Can anyone help me?
My code is:
FileToOpen = Application.GetOpenFilename(FileFilter:="Text Files(*.txt),*txt", MultiSelect:=True)
If IsArray(FileToOpen) Then
Application.ScreenUpdating = False
For i = 1 To UBound(FileToOpen)
Workbooks.OpenText _
Filename:=FileToOpen(i), _
StartRow:=1, _
DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=True, _
Tab:=True, _
Comma:=True, _
FieldInfo:=Array(Array(1, 2), Array(2, 2), Array(3, 2), Array(4, 1), _
Array(5, 2), Array(6, 2), Array(7, 2), Array(8, 2), Array(9, 2))
Set wbTextImport = ActiveWorkbook
wbTextImport.Worksheets(1).Range("A1").CurrentRegion.Copy
wsMaster.Activate
Range("A" & tgRow).Select
ActiveSheet.Paste
Application.CutCopyMode = False
wbTextImport.Close False
wsMaster.Rows(tgRow).Delete Shift:=xlUp
tgRow = wsMaster.Cells(wsMaster.Rows.Count, 1).End(xlUp).Row + 1
Next i

Automate import of .txt files to Excel VBA

I'm trying to automate a report making, i have to copy/paste data from .txt files that are in the same carpet, to do so i use a window because using the path is inefficient when using in other computers.
Errors i encounter:
When saving the new Workbook i use .xlsx or .xls because it throws me an error of data compatibility and the workbook doesn't load or the format is not correct (The format and the extension of the file "My FILE" don't match. The file maybe damaged or not be safe. Dont open it unless you trust the origin ¿ Would you like to open it ?")
I want the data type of all the cells to be text so i can transform the date into dd/mm/yyyy
I have to delete all the spaces that are in the columns so i can add leading zeros into two columns.
I've tried tons of macros i've made but i can't fix the errors.
Here is the latest code i made for the automation, i'm still learning VBA.
Sub REP_DET_Report()
Dim xFd As FileDialog
Dim xFdItem As Variant
Dim xFileName As String
Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
If xFd.Show = -1 Then
xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
xFileName = Dir(xFdItem & "*.txt*")
Do While xFileName <> ""
With Workbooks.Open(xFdItem & xFileName)
Dim objRange1 As Range
'Set up the ranges
Set objRange1 = Range("A1:A1048576")
'Do the first parse
objRange1.TextToColumns _
Destination:=Range("A1"), _
FieldInfo:=Array(Array(1, xlTextFormat), Array(2, xlTextFormat), Array(3, xlTextFormat), Array(4, xlTextFormat), Array(5, xlTextFormat), Array(6, xlTextFormat), Array(7, xlTextFormat), Array(8, xlTextFormat), Array(9, xlTextFormat), Array(10, xlTextFormat)), _
DataType:=xlDelimited, _
Tab:=False, _
Semicolon:=False, _
Comma:=False, _
Space:=False, _
Other:=True, _
OtherChar:="|"
Dim IntialName As String
Dim sFileSaveName As Variant
IntialName = "Sample"
sFileSaveName = Application.GetSaveAsFilename(InitialFileName:=InitialName, FileFilter:="Libro de Excel(*.xls), *.xls")
If sFileSaveName <> False Then
ActiveWorkbook.SaveAs sFileSaveName
End If
End With
xFileName = Dir
Loop
End If
End Sub
Also i made another code so i can paste the .txt in the same workbook but in different worksheets, the issue with this one is that it modifies the first file but the rest don't.
Sub REP_DET_Report()
On Error Resume Next
myBook = ActiveWorkbook.Name
Set nav = CreateObject("shell.application")
folder = nav.browseforfolder(0, "PICK FOLDER", 0, "c:\").items.Item.Path
ChDir folder & "\"
file = Dir("*.txt")
Do While file <> ""
Workbooks.OpenText file, origin:=xlWindows, startrow:=1, DataType:=xlDelimited
Dim objRange1 As Range
'Set up the ranges
Set objRange1 = Range("A1:A1048576")
'Do the first parse
objRange1.TextToColumns _
Destination:=Range("A1"), _
FieldInfo:=Array(Array(1, xlTextFormat), Array(2, xlTextFormat), Array(3, xlTextFormat), Array(4, xlTextFormat), Array(5, xlTextFormat), Array(6, xlTextFormat), Array(7, xlTextFormat), Array(8, xlTextFormat), Array(9, xlTextFormat), Array(10, xlTextFormat)), _
DataType:=xlDelimited, _
Tab:=False, _
Semicolon:=False, _
Comma:=False, _
Space:=False, _
other:=True, _
OtherChar:="|"
other = ActiveWorkbook.Name
ActiveSheet.Copy before:=Workbooks(myBook).Sheets(1)
Workbooks(other).Close False
file = Dir()
Loop
End Sub
´´´

Extract Text File data to worksheet

I want to paste the columns of this text file in my workbook.
USAF-WBAN_ID STATION NAME COUNTRY STATE LATITUDE LONGITUDE ELEVATION
------------ ------------------------------ -------------------------------------------------- ------------------------------ -------- --------- ---------
404200 99999 AL AHSA SAUDI ARABIA +25.285 +049.485 +0179.2
I want to pull 7 variables (7 columns)
USAF-WBAN_ID; STATION NAME; COUNTRY; STATE; LATITUDE; LONGITUDE; ELEVATION
Below is what I've tried in several variations, and results are not reliable.
Sub A1_StationID()
Dim vFile As Variant
Dim wbCopyTo As Workbook
Dim wsCopyTo As Worksheet
Dim wbCopyFrom As Workbook
Dim wsCopyFrom As Worksheet
Set wbCopyTo = ActiveWorkbook
Set wsCopyTo = ActiveSheet
MsgBox "Please select weather stn.txt document"
Dim vFileName
vFileName = Application.GetOpenFilename("Text Files (*.txt), *.txt")
Application.ScreenUpdating = False
Workbooks.OpenText Filename:=vFileName, _
Origin:=xlMSDOS, StartRow:=1, DataType:=xlFixedWidth, _
FieldInfo:=Array(Array(0, 1), Array(13, 1), Array(44, 1), _
Array(127, 1), Array(136, 1), Array(147, 1), Array(154, 1)), _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=False, Comma:=False, Space:=False, _
Other:=False, TrailingMinusNumbers:=True
Set wbCopyFrom = Workbooks.Open(vFileName)
End Sub
Some of the output I get:
If I add a breakpoint on the second to last line of code, I get closer to the output I desire (with messed up columns).
First off - fantastic job posting working code and usable example data.
You were missing the array/field info designation for state and your final 3 columns were ~1/2 characters off. I removed the delimiter options as they don't matter if you're using xlFixedWidth.
Change
Workbooks.OpenText Filename:=vFileName, _
Origin:=xlMSDOS, StartRow:=1, DataType:=xlFixedWidth, _
FieldInfo:=Array(Array(0, 1), Array(13, 1), Array(44, 1), _
Array(127, 1), Array(136, 1), Array(147, 1), Array(154, 1)), _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=False, Comma:=False, Space:=False, _
Other:=False, TrailingMinusNumbers:=True
to
Workbooks.OpenText Filename:=vFileName, _
Origin:=xlMSDOS, StartRow:=1, DataType:=xlFixedWidth, _
FieldInfo:=Array(Array(0, 1), Array(13, 1), Array(44, 1), _
Array(95, 1), Array(126, 1), Array(135, 1), Array(144, 1), Array(154, 1)), _
TextQualifier:=xlDoubleQuote, TrailingMinusNumbers:=True
As a side-note Excel has a bad tendency to remember Text to Columns settings so if you were messing with those earlier, make sure they are set to standard settings.

How to open and extract information from multiple files in VBA

I have around 30 files that I want to perform the same analysis on. Ideally, I want VBA to open all files and extract a certain (identical) piece of information. However, I don't know how to write a function for it. I was thinking of saving all the files as CSV and importing to python (a language I'm familiar with) which would make it easier for my data analysis. The reason I'm importing into excel is because python has difficulty reading .TX0 files (parsing line by line would be time consuming).
This is what i Have for the csv conversion. How do i translate this into the extraction of multiple files?
Sub TX0_CSV()
'
' TX0_CSV Macro
'
'
Workbooks.OpenText Filename:="X/.....fid002.TX0", Origin:= _
xlMSDOS, StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote _
, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, Comma:=True _
, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), Array(2, 1), _
Array(3, 1), Array(4, 1)), TrailingMinusNumbers:=True
Range("A1:O13").Select
Range("O13").Activate
Selection.ClearContents
Rows("15:16").Select
Selection.Delete Shift:=xlUp
ActiveWindow.SmallScroll Down:=9
Range("A20:H29").Select
Range("H29").Activate
Selection.ClearContents
Range("J19").Select
ActiveWorkbook.SaveAs Filename:="X:\Joey\FID002.csv", FileFormat:=xlCSV, _
CreateBackup:=False
End Sub
You could convert it to a sub and then repeatedly call it.
Here is an example (Untested) Also note how we got rid of .Activate and .Select. You may want to see This
Sub ConvertFile(flName As String, newFileName As String)
Dim wb As Workbook
Dim ws As Worksheet
Workbooks.OpenText Filename:=flName, Origin:= _
xlMSDOS, StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote _
, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, Comma:=True _
, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), Array(2, 1), _
Array(3, 1), Array(4, 1)), TrailingMinusNumbers:=True
Set wb = ActiveWorkbook
Set ws = wb.Sheets(1)
With ws
.Range("A1:O13").ClearContents
.Rows("15:16").Delete Shift:=xlUp
.Range("A20:H29").ClearContents
End With
wb.SaveAs Filename:=newFileName, FileFormat:=xlCSV
wb.Close (False)
End Sub
Example
Sub Sample()
ConvertFile "C:\Test1.dat", "C:\Test2.dat"
End Sub

Resources