I have a code to open text files to copy included data and paste it in the excel file, but while select multiple files the code run only for one file and i want to run it for all selectet files
CWB is the main file
NWB is the file to copy from it
The code
Sub Import_Reports()
' Difine References
Dim CWB As Excel.Workbook
Dim NWB As Excel.Workbook
Dim FN As String
Dim FD As FileDialog
Set CWB = ThisWorkbook
Set FD = Application.FileDialog(msoFileDialogFilePicker)
With FD
.AllowMultiSelect = True
.Filters.Add "Excel Files or Text or CSV", "*.xls; *.xlsx; *.xlsm; *.xlsb; *.csv; *.txt", 1
.Show
If .SelectedItems.Count > 0 Then
FN = .SelectedItems(1)
Workbooks.OpenText Filename:=FN, _
Origin:=65001, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _
Comma:=True, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 2), _
Array(2, 2), Array(3, 2), Array(4, 4), Array(5, 1), Array(6, 2), Array(7, 2), Array(8, 2), _
Array(9, 4), Array(10, 1), Array(11, 1), Array(12, 4), Array(13, 2), Array(14, 2), Array(15 _
, 1), Array(16, 1), Array(17, 4), Array(18, 4), Array(19, 1), Array(20, 1), Array(21, 1), _
Array(22, 1)), TrailingMinusNumbers:=True
Set NWB = ActiveWorkbook
NWB.Activate
ActiveSheet.Select
Dim LastRow As Long
LastRow = Range("B" & Rows.Count).End(xlUp).Row
Range("A2:V" & LastRow).Select
Selection.Copy
CWB.Activate
Sheets("Payroll Report").Select
LastRow = Range("B" & Rows.Count).End(xlUp).Row + 1
Range("A" & LastRow).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Cells.Select
Selection.SpecialCells(xlCellTypeLastCell).Select
Selection.EntireRow.Delete
Range("A" & LastRow).Select
NWB.Close SaveChanges:=False
Else
Exit Sub
End If
End With
End Sub
Move the copying code to a separate subroutine that you can call for each file.
Option Explicit
Sub Import_Reports()
' Define References
Dim CWB As Excel.Workbook
Dim FD As FileDialog, n
Set CWB = ThisWorkbook
Set FD = Application.FileDialog(msoFileDialogFilePicker)
With FD
.AllowMultiSelect = True
.Filters.Add "Excel Files or Text or CSV", "*.xls; *.xlsx; *.xlsm; *.xlsb; *.csv; *.txt", 1
.Show
If .SelectedItems.Count = 0 Then Exit Sub
For n = 1 To .SelectedItems.Count
Call ImportTextFile(CWB, .SelectedItems(n))
Next
End With
MsgBox n - 1 & " files imported", vbInformation
End Sub
Sub ImportTextFile(CWB As Workbook, filename As String)
Workbooks.OpenText filename:=filename, _
Origin:=65001, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _
Comma:=True, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 2), _
Array(2, 2), Array(3, 2), Array(4, 4), Array(5, 1), Array(6, 2), Array(7, 2), Array(8, 2), _
Array(9, 4), Array(10, 1), Array(11, 1), Array(12, 4), Array(13, 2), Array(14, 2), Array(15 _
, 1), Array(16, 1), Array(17, 4), Array(18, 4), Array(19, 1), Array(20, 1), Array(21, 1), _
Array(22, 1)), TrailingMinusNumbers:=True
Dim LastRow As Long, ar
With ActiveWorkbook.Sheets(1)
LastRow = .Range("B" & .Rows.Count).End(xlUp).Row
' copy values to array except last row
ar = .Range("A2:V" & LastRow - 1).Value2
End With
ActiveWorkbook.Close SaveChanges:=False
' copy array to CWB
With CWB.Sheets("Payroll Report")
LastRow = .Range("B" & .Rows.Count).End(xlUp).Row + 1
.Range("A" & LastRow).Resize(UBound(ar), UBound(ar, 2)) = ar
End With
End Sub
Import Text Files
Option Explicit
Sub Import_Reports()
Dim FD As FileDialog
Set FD = Application.FileDialog(msoFileDialogFilePicker)
Dim collFilePaths As Object
With FD
.AllowMultiSelect = True
.Filters.Add "Excel Files or Text or CSV", "*.xls; *.xlsx; *.xlsm; *.xlsb; *.csv; *.txt", 1
.Show
If .SelectedItems.Count = 0 Then
MsgBox "You canceled.", vbExclamation
Exit Sub
Else
Set collFilePaths = .SelectedItems
End If
End With
Dim CWB As Workbook: Set CWB = ThisWorkbook
Dim cws As Worksheet: Set cws = CWB.Worksheets("Payroll Report")
Dim cfrrg As Range
Set cfrrg = cws.Range("B" & cws.Rows.Count).End(xlUp) _
.Offset(1).EntireRow.Columns("A:V")
Application.ScreenUpdating = False
Dim FilePath As Variant
Dim NWB As Workbook
Dim nws As Worksheet
Dim nrg As Range
Dim nLastRow As Long
Dim crg As Range
For Each FilePath In collFilePaths
'Set NWB = Workbooks.Open(FilePath) ' tested with this line
On Error Resume Next
Set NWB = Workbooks.OpenText(Filename:=CStr(FilePath), _
Origin:=65001, StartRow:=1, DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, _
Tab:=True, Semicolon:=False, Comma:=True, Space:=False, _
Other:=False, FieldInfo:=Array(Array(1, 2), Array(2, 2), _
Array(3, 2), Array(4, 4), Array(5, 1), Array(6, 2), _
Array(7, 2), Array(8, 2), Array(9, 4), Array(10, 1), _
Array(11, 1), Array(12, 4), Array(13, 2), Array(14, 2), _
Array(15, 1), Array(16, 1), Array(17, 4), Array(18, 4), _
Array(19, 1), Array(20, 1), Array(21, 1), Array(22, 1)), _
TrailingMinusNumbers:=True)
On Error GoTo 0
If Not NWB Is Nothing Then
Set nws = NWB.Worksheets(1)
' Delete last row = Don't Copy Last row - '- 1' ???
nLastRow = nws.Range("B" & nws.Rows.Count).End(xlUp).Row - 1
If nLastRow >= 2 Then
Set nrg = nws.Range("A2:V" & nLastRow)
nLastRow = nLastRow - 1
Set crg = cfrrg.Resize(nLastRow)
crg.Value = nrg.Value
Set cfrrg = cfrrg.Offset(nLastRow)
End If
NWB.Close SaveChanges:=False
Set NWB = Nothing
End If
Next FilePath
cws.Activate
cfrrg.Cells(1).Select
'CWB.Save
Application.ScreenUpdating = True
MsgBox "Reports imported.", vbInformation
End Sub
Related
I am using software which generates a logfile everyday, and my technicians need to check the logs and I want to make it as easy as possible, I have a script that was used previously, where the techs enter the first and last date in cells M2 and O2 these dates are then converted to the format which corresponds to the file name:
Sheets("Intake reports").Select
Range("M2").Select 'Get date of 1st day
BCDate = ActiveCell
Application.ScreenUpdating = False
BCday = Left(BCDate, 2)
BCmonth = Mid(BCDate, 4, 2)
BCyear = Right(BCDate, 2)
BCDate1st = BCyear + BCmonth + BCday
Range("O2").Select 'Get date of 2nd day
BCDate = ActiveCell
Application.ScreenUpdating = False
BCday = Left(BCDate, 2)
BCmonth = Mid(BCDate, 4, 2)
BCyear = Right(BCDate, 2)
BCDate2nd = BCyear + BCmonth + BCday
Application.DisplayAlerts = False
Then it opens the two files and copies them into a worksheet:
'Load 1st BC log file
'
Workbooks.OpenText Filename:="C:\Users\1548013\Desktop\Logfiles\BC" + BCDate1st + ".LOG", Origin:= _
xlMSDOS, StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote _
, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, Comma:= _
False, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), Array(2, 1) _
, Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), Array(7, 1), Array(8, 1), Array(9, 1), _
Array(10, 1), Array(11, 1), Array(12, 1), Array(13, 1), Array(14, 1), Array(15, 1), Array( _
16, 1), Array(17, 1), Array(18, 1), Array(19, 1), Array(20, 1), Array(21, 1), Array(22, 1), _
Array(23, 1), Array(24, 1), Array(25, 1)), TrailingMinusNumbers:=True
LastRow1st = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
'Selection.SpecialCells(xlCellTypeLastCell).Select Line 1 of 2
'TheLastRow = ActiveCell.Row Line 2 of 2
Range("a1:x" & LastRow1st).Select
Selection.Copy
' Windows("Log Template.xlsm").Activate
Windows("filename.xlsm").Activate
Sheets("LogTemplate").Select
Range("A1").Select
ActiveSheet.Paste
Windows("BC" + BCDate1st + ".LOG").Activate
ActiveWindow.Close
Application.DisplayAlerts = False
' Workbooks.OpenText Filename:="I:\KMcK\LogFiles\BC" + BCDate2nd + ".LOG", Origin:=
'Load 2nd BC log file
Workbooks.OpenText Filename:="C:\Users\1548013\Desktop\Logfiles\BC" + BCDate2nd + ".LOG", Origin:= _
xlMSDOS, StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote _
, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, Comma:= _
False, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), Array(2, 1) _
, Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), Array(7, 1), Array(8, 1), Array(9, 1), _
Array(10, 1), Array(11, 1), Array(12, 1), Array(13, 1), Array(14, 1), Array(15, 1), Array( _
16, 1), Array(17, 1), Array(18, 1), Array(19, 1), Array(20, 1), Array(21, 1), Array(22, 1), _
Array(23, 1), Array(24, 1), Array(25, 1)), TrailingMinusNumbers:=True
LastRow2nd = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
Range("a1:x" & LastRow2nd).Select
Selection.Copy
Windows("filename").Activate
' Windows("filename").Activate
Sheets("LogTemplate").Select
Range("A" & LastRow1st + 1).Select
ActiveSheet.Paste
Windows("BC" + BCDate2nd + ".LOG").Activate
ActiveWindow.Close
This only works for two consecutive days, as each day is a separate file. I would like to enter the start date of the study in M2 and today's date in o2 and the script opens and imports every file between the two dates (inclusive).
thanks in advance
Option Explicit
Sub IntakeReports()
Const FOLDER = "C:\Users\1548013\Desktop\Logfiles\" '
Dim wb As Workbook
Dim rngSrc As Range, rngTarget As Range
Dim dtFirst As Date, dtLast As Date, dt As Date
Dim n As Long, i As Long
Dim logfile As String, msg As String
Set wb = ThisWorkbook
With wb.Sheets("IntakeReports")
dtFirst = .Range("M2").Value2
dtLast = Now
End With
n = DateDiff("d", dtFirst, dtLast) + 1
If n < 1 Then
MsgBox "End date must be after start date", vbCritical
Exit Sub
Else
msg = Format(dtFirst, "dd-mmm-yy") & " to " & _
Format(dtLast, "dd-mmm-yy") & vbLf & _
vbLf & "Read " & n & " reports ?"
If vbNo = MsgBox(msg, vbYesNo, "Confirm") Then
Exit Sub
End If
msg = ""
End If
' select report folder
Dim fso As Object, sFolder As String
Set fso = CreateObject("Scripting.FileSystemObject")
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please select a folder"
.InitialFileName = FOLDER
.Show
.AllowMultiSelect = False
If .SelectedItems.Count = 0 Then 'If no folder is selected, abort
MsgBox "You did not select a folder"
Exit Sub
End If
sFolder = .SelectedItems(1) 'Assign selected folder to ParentFolder
End With
If Right(sFolder, 1) <> "\" Then sFolder = sFolder & "\"
' target cell for copy
Set rngTarget = wb.Sheets("LogTemplate").Range("A1")
' loop though dates
Application.ScreenUpdating = False
n = 0
For dt = dtFirst To dtLast
logfile = "BC" & Format(dt, "yymmdd") & ".LOG"
' check file exists
If fso.FileExists(sFolder & logfile) Then
Workbooks.OpenText Filename:=sFolder & logfile, Origin:= _
xlMSDOS, StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote _
, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, Comma:= _
False, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), Array(2, 1) _
, Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), Array(7, 1), Array(8, 1), Array(9, 1), _
Array(10, 1), Array(11, 1), Array(12, 1), Array(13, 1), Array(14, 1), Array(15, 1), Array( _
16, 1), Array(17, 1), Array(18, 1), Array(19, 1), Array(20, 1), Array(21, 1), Array(22, 1), _
Array(23, 1), Array(24, 1), Array(25, 1)), TrailingMinusNumbers:=True
With ActiveWorkbook
Set rngSrc = .Sheets(1).UsedRange
rngSrc.Copy rngTarget
Set rngTarget = rngTarget.Offset(rngSrc.Rows.Count)
.Close
End With
i = i + 1
Else
n = n + 1
msg = msg & vbLf & logfile
End If
Next
Application.ScreenUpdating = True
' result
If n > 0 Then msg = vbLf & n & " logs not found" & msg
msg = i & " logs found" & msg
MsgBox msg, vbInformation, sFolder
End Sub
We have a mission critical spreadsheet that imports a lot of flat text from a desgin program and then brings it in to this spreadsheet.
We recently updated the design software, which we do once a year and have done so in my 12 years here. This year, they made a change to a file where it placed the header of a column of text in a different place. Now, our program will not import it correctly. It is the PART column...
Old text file:
New Text File...
So as you can see, they moved PART to the lower left.
Not being an expert in VBA, I am struggling to find exactly where I need to modify the code to bring it in properly..
This is the section of VBA code where I do think the selections are made but nothing specifies PART in the code...perhaps it is part of the Array? The file is called CZE_DET.OUT.
Sub IMPORT_CZEOUT()
Dim aryJobs() As String
Dim strComb As String
Dim strDir As String
Dim i As Integer
Dim j As Integer
Dim k As Integer
Sheets("CEE ORDER").Visible = True
Sheets("CZE_DET").Visible = True
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Sheets("CEE ORDER").Select
For i = 1 To colAllBuildings.Count
strDir = Dir$(colAllBuildings.Item(i) & "\CZE_DET.OUT")
If strDir <> "" Then
Workbooks.OpenText Filename:=colAllBuildings.Item(i) & "\CZE_DET.OUT", Origin:=xlWindows, _
StartRow:=7, DataType:=xlFixedWidth, _
FieldInfo:=Array(Array(0, 9), Array(5, 1), Array(9, 9), Array(10, 1), _
Array(13, 9), Array(14, 1), Array(15, 9), Array(16, 1), Array(18, 1), _
Array(28, 9), Array(35, 9), Array(47, 9), Array(54, 1), Array(57, 1), _
Array(62, 1), Array(67, 1), Array(72, 1))
Range("A1:L" & CStr(Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row)).Select
Selection.Copy
Windows(strShipperName).Activate ' This line does not work, for NO reason!
' Windows(1).ActivatePrevious
Sheets("CZE_DET").Select
Range("A1").Select
If Range("A1").Value <> "" Then
ActiveSheet.Range("A65536").End(xlUp).Select
ActiveCell.Offset(1, 0).Select
End If
Selection.PasteSpecial Paste:=xlValues
Selection.Sort Key1:=Range("A12"), Order1:=xlAscending, Orientation:=xlTopToBottom
Windows("CZE_DET.OUT").Activate
ActiveWindow.Close
End If
Next
I would post the spreadsheet but it attaches the VBA though an XLA file through a network share. And the XLA file is protected and I can't seem to rename it and remove password to send a link.
I posted the entire subroutine here as I only posted where I thought t the problem would be: https://pinnaclestructures365-my.sharepoint.com/:f:/g/personal/bwolters_pinnaclestructures_com/EpGrxtGx4_BCgL4nl3QDZxcBalaRSL52pI0S8UNX0n6kOg?e=0oyh2k
Any suggestions?
Here is a re-worked example of how to make your references more explicit.
Sub IMPORT_CZEOUT()
Dim aryJobs() As String
Dim strComb As String
Dim strDir As String
Dim i As Integer, cDest As Range
Dim j As Integer, fName As String, rngData As Range, lRow As Long
Dim k As Integer, wb As Workbook, wbSrc As Workbook, wsSrc As Worksheet
Set wb = Workbooks(strShipperName) 'The wb where data is to be collected
'Include the file extension!
wb.Sheets("CEE ORDER").Visible = True
wb.Sheets("CZE_DET").Visible = True
Application.DisplayAlerts = False
Application.ScreenUpdating = False
For i = 1 To colAllBuildings.Count
fName = colAllBuildings.Item(i) & "\CZE_DET.OUT"
If Len(Dir(fName)) > 0 Then
Workbooks.OpenText Filename:=fName, Origin:=xlWindows, _
StartRow:=7, DataType:=xlFixedWidth, _
FieldInfo:=Array(Array(0, 9), Array(5, 1), Array(9, 9), Array(10, 1), _
Array(13, 9), Array(14, 1), Array(15, 9), Array(16, 1), Array(18, 1), _
Array(28, 9), Array(35, 9), Array(47, 9), Array(54, 1), Array(57, 1), _
Array(62, 1), Array(67, 1), Array(72, 1))
Set wbSrc = ActiveWorkbook 'source data workbook
Set wsSrc = wbSrc.Worksheets(1) 'source data sheet
lRow = wsSrc.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Set rngData = wsSrc.Range("A1:L" & lRow) 'all source data
With wb.Worksheets("CZE_DET") 'EDIT
Set cDest = .Cells(.Rows.Count, "A").End(xlUp)
End With
If Len(cDest.Value) > 0 Then Set cDest = cDest.Offset(1)
cDest.Resize(rngData.Rows.Count, rngData.Columns.Count).Value = rngData.Value
'not sure about this line....
Selection.Sort Key1:=Range("A12"), Order1:=xlAscending, Orientation:=xlTopToBottom
wbSrc.Close savechanges:=False 'close the source file
End If
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
EDIT - as pointed out in a comment, the length of one of the fileds has increased by 1 character, so the FieldInfo argument needs to be updated:
Workbooks.OpenText Filename:=fName, Origin:=xlWindows, _
StartRow:=7, DataType:=xlFixedWidth, _
FieldInfo:=Array(Array(0, 9), Array(5, 1), Array(9, 9), Array(10, 1), _
Array(13, 9), Array(14, 1), Array(15, 9), Array(16, 1), Array(18, 1), _
Array(28, 9), Array(35, 9), Array(47, 9), Array(55, 1), Array(58, 1), _
Array(63, 1), Array(68, 1), Array(73, 1))
The open statement could be simplified as the skipped fields (type=9) are the blanks and values are trimmed on import.
Workbooks.OpenText Filename:=s, Origin:=xlWindows, _
StartRow:=7, DataType:=xlFixedWidth, _
FieldInfo:=Array(Array(0, 9), Array(4, 1), Array(18, 1), Array(27, 1), _
Array(35, 1), Array(54, 1), Array(58, 1), _
Array(63, 1), Array(68, 1), Array(73, 1))
Tested with this text file
line 1
line 2
line 3
line 4
line 5
line 6
ish description part punch comment qnt feet inch 16th mark
--- ------------- -------- ------- ------------------ --- ---- ---- ---- ------
xxx 8.0x3.5 c 12 8x35c12 psu-psu see drawing ec-1 28 16 8 3 ec-1
xxx 8.0x3.5 c 12 8x35c12 psu-psu see drawing ec-1 28 16 8 3 ec-1
xxx 8.0x3.5 c 12 8x35c12 psu-psu see drawing ec-1 28 16 8 3 ec-1
a-z a-----------z a----- z a-----z a----------------z a-z a--z a--z a--z a----z
My Excel VBA script pulls data from other files, and my script isn't very good. How can I speed the file up?
So I pull 11x2737 data from each of 8 text files and pull 3x70101 from each of another 8 text files. It takes over 2 minutes to do this.
Set conFolder = CreateObject("Scripting.FileSystemObject")
For Each conFile In conFolder.GetFolder(folderName).Files
If InStr(conFile, "con.dat") > 0 Then
Set WorkB4 = Workbooks.Open(Filename:=conFile)
WorkB4.Activate
WorkB4.Application.DisplayAlerts = False
Columns("A:A").Select
Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), _
Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1)), _
TrailingMinusNumbers:=True
Cells.Select
Selection.Copy
conBottle = Left(Right(conFile, 9), 1)
WorkB1.Activate
Sheets("Bot" & conBottle).Select
Range("A1").Select
ActiveSheet.Paste
WorkB4.Application.DisplayAlerts = True
WorkB4.Application.CutCopyMode = False
WorkB4.Close SaveChanges:=False
End If
Next
I'm hoping there's a way to pull this data as fast as possible (ideally within 5 seconds).
Avoiding Select and Activate, turning off ScreenUpdating, and skipping the clipboard should help, but typically the biggest bottleneck would be network or disk I/O: if the text files are on a network share, try copying them locally first.
So I refactored the code a bit, and there's only WorkB1 I couldn't work out where it came from.
None of this is tested, but it should give you a workable starting point.
Option Explicit
Public Sub ProcessFiles(ByVal Path As String)
Dim WorkB1 As Workbook ' <~
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlCalculationManual
On Error GoTo CleanFail
With CreateObject("Scripting.FileSystemObject")
Dim conFolder As Object
Set conFolder = .GetFolder(Path)
Dim conFile As Variant '/String
For Each conFile In conFolder.Files
If InStr(conFile, "con.dat", VbCompareMethod.vbTextCompare) > 0 Then
ProcessFile conFile, WorkB1
End If
Next
End With
CleanExit:
Application.ScreenUpdating = True
Application.DisplayAlerts = False
Application.Calculation = xlCalculationAutomatic
Exit Sub
CleanFail:
Debug.Print Err.Description
Resume CleanExit
End Sub
Private Sub ProcessFile(ByVal conFile As String, ByVal WorkB1 As Workbook)
On Error GoTo CleanFail
Dim book As Workbook
Set book = Workbooks.Open(conFile)
Dim sheet As Worksheet
Set sheet = book.Worksheets(1)
Dim dataRange As Range
Set dataRange = sheet.Columns(1)
Const NumberOfColumns As Long = 11
dataRange.TextToColumns _
destination:=sheet.Range("A1"), _
DataType:=xlDelimited, _
TextQualifier:=xlTextQualifierDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, _
Semicolon:=False, _
Comma:=True, _
Space:=False, _
Other:=False, _
FieldInfo:=Array( _
Array(1, 1), _
Array(2, 1), _
Array(3, 1), _
Array(4, 1), _
Array(5, 1), _
Array(6, 1), _
Array(7, 1), _
Array(8, 1), _
Array(9, 1), _
Array(10, 1), _
Array(11, 1)), _
TrailingMinusNumbers:=True
Dim dataRows As Long
dataRows = sheet.Range("A" & sheet.Rows.Count).End(xlUp).Row
Dim sourceRange As Range
Set sourceRange = sheet.Range("A1", sheet.Cells(dataRows, NumberOfColumns))
Debug.Print "Source: " & sourceRange.Address(External:=True)
Dim conBotName As String
conBotName = Left$(Right$(conFile, 9), 1)
Dim conBotSheet As Worksheet
Set conBotSheet = WorkB1.Worksheets("Bot" & conBotName)
Dim destination As Range
Set destination = conBotSheet.Range("A1", conBotSheet.Cells(dataRows, NumberOfColumns))
Debug.Print "Destination: " & destination.Address(External:=True)
destination.Value = sourceRange.Value
book.Close SaveChanges:=False
CleanExit:
Exit Sub
CleanFail:
Debug.Print Err.Description
Resume CleanExit
End Sub
I've had this Macro button built. I'm getting an error immediately after pressing the button as this was designed to work on a PC.
The file is just asking for the location of the excel file to format. I just need this to work on a Mac so can someone change the code to allow opening of files from a Mac environment instead of a Windows one?
This is the Visual Basic editor;
Sub Johnny_Calculations()
Dim TotalRow As String
Dim wb As String
Dim ws As String
With Application.FileDialog(msoFileDialogOpen)
.Show
.Title = "Choose File"
.AllowMultiSelect = False
If .SelectedItems.Count = 1 Then
Path = .SelectedItems(1)
End If
End With
Workbooks.OpenText Filename:= _
Path _
, Origin:=xlWindows, StartRow:=1, DataType:=xlDelimited, TextQualifier _
:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:= _
True, Comma:=False, Space:=False, Other:=False, FieldInfo:=Array(Array( _
1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), Array(7, 1), Array(8, _
1), Array(9, 1), Array(10, 1), Array(11, 1), Array(12, 1), Array(13, 1), Array(14, 1), Array _
(15, 1), Array(16, 1), Array(17, 1), Array(18, 1), Array(19, 1), Array(20, 1), Array(21, 1), _
Array(22, 1), Array(23, 1)), TrailingMinusNumbers:=True
wb = ActiveWindow.Caption
ws = ActiveSheet.Name
TotalRow = WorksheetFunction.Match("Total", Range("A:A"), 0)
Rows(TotalRow & ":" & TotalRow).Select
Selection.ClearContents
File = "Johnny Calculations.xlsm"
Workbooks(File).Worksheets("Sheet2").Activate
Workbooks(File).Worksheets("Sheet1").Range("B2:C22").Copy
Windows(wb). _
Activate
Sheets.Add After:=ActiveSheet
Range("B2").Select
ActiveSheet.Paste
Columns("B:C").Select
Selection.ColumnWidth = 16.86
Range("C3").Select
Application.CutCopyMode = False
'calculations
ActiveCell.FormulaR1C1 = "=SUM('" & wb & "'!C)"
Range("C6").Select
ActiveCell.FormulaR1C1 = "=SUM('" & wb & "'!C[3])"
Range("C7").Select
ActiveCell.FormulaR1C1 = "=R[-1]C/R[-4]C"
Range("C7").Select
Range("C8").Select
ActiveCell.FormulaR1C1 = _
"=SUM('" & wb & "'!C[4])/SUM('" & wb & "'!C)"
Range("C10").Select
ActiveCell.FormulaR1C1 = "=SUM('" & wb & "'!C[5])"
Range("C11").Select
ActiveCell.FormulaR1C1 = _
"=SUM('" & wb & "'!C[5])/SUM('" & wb & "'!C[4])"
Range("C12").Select
ActiveCell.FormulaR1C1 = _
"=SUM('" & wb & "'!C[6])/SUM('" & wb & "'!C[3])"
Range("C13").Select
ActiveCell.FormulaR1C1 = "=R[-3]C/R[-7]C"
Range("C15").Select
ActiveCell.FormulaR1C1 = "=SUM('" & wb & "'!C[7])"
Range("C16").Select
ActiveCell.FormulaR1C1 = "=R[-1]C/R[-6]C"
Range("C17").Select
ActiveCell.FormulaR1C1 = "=SUM('" & wb & "'!C[10])"
Range("C19").Select
ActiveCell.FormulaR1C1 = "=SUM('" & wb & "'!C[8])"
Range("C20").Select
ActiveCell.FormulaR1C1 = "=IFERROR(R[-1]C/R[-5]C,""No Complaints"")"
Range("C21").Select
ActiveCell.FormulaR1C1 = "=SUM('" & wb & "'!C[9])"
Range("C22").Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = "=R[-1]C/R[-19]C"
Range("C23").Select
End Sub
I am reusing code Import Multiple text files into workbook where worksheet name matches text file name
This code is creating multiple worksheets and importing pipe delimited data into individual columns.
I need all the cells to be set to Text qualified before it does the text to columns.
Basically I want all the columns to be in text format instead of default General as the 16 digit numbers that I have in my file are getting messed up with General format.
I did try to put below lines but it changes the format after text to column is completed.
cells.select
Selection.NumberFormat = "#"
Here is the code that I am using
Sub Extract()
Dim FilesToOpen
Dim x As Integer
Dim wkbAll As Workbook
Dim sDelimiter As String
On Error GoTo ErrHandler
Application.ScreenUpdating = False
sDelimiter = "|"
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
If TypeName(FilesToOpen) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
Set wkbAll = Application.ActiveWorkbook
x = 1
With Workbooks.Open(Filename:=FilesToOpen(x))
.Worksheets(1).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
.Sheets(1).Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
.Close False
End With
x = x + 1
While x <= UBound(FilesToOpen)
With Workbooks.Open(Filename:=FilesToOpen(x))
.Worksheets(1).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:=sDelimiter
.Sheets(1).Move After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
End With
x = x + 1
Wend
wkbAll.Save
ExitHandler:
Application.ScreenUpdating = True
Set wkbAll = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub
Try this (I haven't). It (hopefully) sets all cells in the sheet to text. With see commented section for the addition.
Sub Extract()
Dim FilesToOpen
Dim x As Integer
Dim wkbAll As Workbook
Dim sDelimiter As String
On Error GoTo ErrHandler
Application.ScreenUpdating = False
sDelimiter = "|"
FilesToOpen = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
If TypeName(FilesToOpen) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
Set wkbAll = Application.ActiveWorkbook
x = 1
With Workbooks.Open(Filename:=FilesToOpen(x))
' ---------------------------------------------------
.Worksheets(1).Cells.NumberFormat = "#"
' ---------------------------------------------------
.Worksheets(1).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
.Sheets(1).Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
.Close False
End With
x = x + 1
While x <= UBound(FilesToOpen)
With Workbooks.Open(Filename:=FilesToOpen(x))
.Worksheets(1).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:=sDelimiter
.Sheets(1).Move After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
End With
x = x + 1
Wend
wkbAll.Save
ExitHandler:
Application.ScreenUpdating = True
Set wkbAll = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub
Not the permanent solution but I added below change which looks like resolved my problem. Since the longest record in one of my file has 45 cells I auto recorded below Macro and appended to my code after OtherChar:="|" and now it is working as I wanted.
OtherChar:="|", FieldInfo:=Array(Array(1, 2), Array(2, 2), Array(3, 2), Array(4, 2), Array(5, _
2), Array(6, 2), Array(7, 2), Array(8, 2), Array(9, 2), Array(10, 2), Array(11, 2), Array(12 _
, 2), Array(13, 2), Array(14, 2), Array(15, 2), Array(16, 2), Array(17, 2), Array(18, 2), _
Array(19, 2), Array(20, 2), Array(21, 2), Array(22, 2), Array(23, 2), Array(24, 2), Array( _
25, 2), Array(26, 2), Array(27, 2), Array(28, 2), Array(29, 2), Array(30, 2), Array(31, 2), _
Array(32, 2), Array(33, 2), Array(34, 2), Array(35, 2), Array(36, 2), Array(37, 2), Array( _
38, 2), Array(39, 2), Array(40, 2), Array(41, 2), Array(42, 2), Array(43, 2), Array(44, 2), _
Array(45, 2)), TrailingMinusNumbers:=True