Import fixed text file into excel using VBA - vba

I'm working with importing a fixed text file into excel file using VBA.
I had a problem fixing the fitting of columns (auto fit) also with the decimal of numbers.
I have a Decimal as much as this 5027.1202024.0000.0000.000.0000.0000.0000 and would like to simplified to just 5027.12 since my columns is not fitting and just separating. is there another way besides declaring several arrays and fixing it's width? the text file is somehow fixed already.
I'm still new to vba I would appreaciate every help. Thanks
EDIT:
Option Explicit
Sub ImportPrepayment()
Dim fpath
Dim x As Integer
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim sDelimiter As String
'Call import_TExtFileR12
On Error GoTo ErrHandler
Application.ScreenUpdating = False
sDelimiter = "|"
fpath = Application.GetOpenFilename _
(FileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Text Files to Open")
If TypeName(fpath) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
x = 1
Set wkbTemp = Workbooks.Open(FileName:=fpath(x))
wkbTemp.Sheets(1).Copy
Set wkbAll = ActiveWorkbook
wkbTemp.Close (False)
wkbAll.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:="|"
x = x + 1
While x <= UBound(fpath)
Set wkbTemp = Workbooks.Open(FileName:=fpath(x))
With wkbAll
wkbTemp.Sheets(1).Move After:=.Sheets(.Sheets.Count)
.Worksheets(x).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
End With
x = x + 1
Wend
Range("A17:XFD" & x).Delete shift:=xlUp
'Range("A1").Value = "Supplier Name"
' Range("C1").Value = "Supplier Number"
'Range("D1").Value = "Inv Curr Code"
'Range("E1").Value = "Payment Cur Code"
'Range("F1").Value = "Invoice Type"
'Range("G1").Value = "Invoice Number"
'Range("H1").Value = "Voucher Number"
'Range("I1").Value = "Invoice Date"
'Range("J1").Value = "GL Date"
'Range("K1").Value = "Invoice Amount"
'Range("L1").Value = "Witheld Amount"
'Range("M1").Value = "Amount Remaining"
'Range("N1").Value = "Description"
'Range("O1").Value = "Account Number"
'Range("P1").Value = "Invoice Amt"
'Range("Q1").Value = "Withheld Amt"
'Range("R1").Value = "Amt Remaining"
'Range("S1").Value = "User Name"
Call ProcessUsedRange
Columns.EntireColumn.HorizontalAlignment = xlCenter
Columns.EntireColumn.AutoFit
ExitHandler:
Application.ScreenUpdating = True
Set wkbAll = Nothing
Set wkbTemp = Nothing
Exit Sub
ErrHandler:
If Err.Number <> 0 Then MsgBox Err.Number & " " & Err.Description
Resume ExitHandler
End Sub
Sub ProcessUsedRange()
Dim r As Range
Dim regex As Object, Match As Object
Set regex = CreateObject("VBScript.RegExp")
With regex
.Pattern = "\d{4}.\d{4}.\d{4}.\d{3}.\d{4}.\d{4}.\d{4}"
.Global = True
End With
For Each r In ActiveSheet.UsedRange
If regex.Test(r.Text) Then
For Each Match In regex.Execute(r.Value)
r.Value = "'" & Replace(r.Value, Match.Value, "")
Next
End If
Next
End Sub

Instead of using TextToColumns or Workbooks.OpenText; just read the text file and process the data.
Sub ImportPrepayment2()
Dim fpath As Variant
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim Text As String
On Error GoTo terminatemsg
Set wb = Excel.ActiveWorkbook
Set ws = Excel.ActiveSheet
fpath = Application.GetOpenFilename(Filefilter:="text Files(*.txt; *.txt), *.txt; *.txt", Title:="open")
If fpath = False Then Exit Sub
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Text = getTextfileData(fpath)
If Len(Text) Then
ProcessData Text
AdjustDates
Else
MsgBox fpath & " is empty", vbInformation, "Import Cancelled"
Exit Sub
End If
Columns.EntireColumn.AutoFit
Sheets(1).Move Before:=wb.Sheets(1)
terminatemsg:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
If Err.Number <> 0 Then MsgBox Err.Number & " " & Err.Description
End Sub
Sub ProcessData(Text As String)
Dim x As Long, y As Long, z As Long
Dim data, vLine
data = Split(Text, vbCrLf)
x = 2
Range("A1:R1").Value = Array("Supplier Name", "Supplier Number", "Inv Curr Code CurCode", "Payment CurCode", "Invoice Type", "Invoice Number", "Voucher Number", "Invoice Date", "GL Date", "Invoice Amount", "Withheld Amount", "Amount Remaining", "Description", "Account Number", "Invoice", "Withheld", "Amt", "User")
For y = 0 To UBound(data)
If InStr(data(y), "|") Then
vLine = Split(data(y), "|")
If Not Trim(vLine(0)) = "Supplier" Then
For z = 0 To UBound(vLine)
vLine(z) = Trim(vLine(z))
If vLine(z) Like "*.*.*.*.*.*.*.*" Then vLine(z) = Left(vLine(z), InStr(vLine(z), ".") + 2)
Next
Cells(x, 1).Resize(1, UBound(vLine) + 1).Value = vLine
x = x + 1
End If
End If
Next
End Sub
Sub AdjustDates()
Dim x As Long
For x = 2 To Range("B" & Rows.Count).End(xlUp).row
If Cells(x, "R") = vbNullString Then Cells(x, "M").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Next
End Sub
Function getTextfileData(FILENAME As Variant) As String
Const ForReading = 1
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.OpenTextFile(FILENAME, ForReading)
getTextfileData = MyFile.ReadAll
MyFile.Close
End Function

Add this code before Columns.EntireColumn.AutoFit.
Sub ProcessUsedRange()
Dim r As Range
Dim regex As Object, Match As Object
Set regex = CreateObject("VBScript.RegExp")
With regex
.Pattern = "\d{4}.\d{4}.\d{4}.\d{3}.\d{4}.\d{4}.\d{4}"
.Global = True
End With
For Each r In ActiveSheet.UsedRange
If regex.Test(r.Text) Then
For Each Match In regex.Execute(r.Value)
'The apostrophe is to keep the data formatted as text
r.Value = "'" & Replace(r.Value, Match.Value, "")
Next
End If
Next
End Sub
You should also change
MsgBox Err.Number & " " & Err.Description
to
If Err.Number <> 0 then MsgBox Err.Number & " " & Err.Description

Related

Macro runs on PC but not on MacOS: Subscript out of range error

I can get this code to run on PC but not on Mac. The code allows you to select text files and convert them into worksheets and append them to your current workbook.
Set wkbTemp = Workbooks.Open(FileName:=FilesToOpen(x))
The above line of code is sending the program to the Error Handler and causing a subscript out of range error.
In the link below is a picture of the Locals Window that shows the path name from the file I wish to grab.
https://imgur.com/a/wPzH5VB
Sub CombineTextFiles()
Dim FilesToOpen
Dim x As Integer
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim sDelimiter As String
Dim answer As Integer
On Error GoTo ErrHandler
Application.ScreenUpdating = False
answer = MsgBox("Before moving forward, all other workbooks must be closed" _
& vbCrLf & "Do you wish to continue?", vbYesNo + vbQuestion)
If answer = vbYes Then 'do nothing
Else: Exit Sub
End If
sDelimiter = ","
#If Mac Then
FilesToOpen = Select_File_Or_Files_Mac()
#Else
FilesToOpen = Application.GetOpenFilename(fileFilter:="Text Files (*.txt), *.txt", _
MultiSelect:=True, Title:="Select the CDR Text Files to Open")
#End If
If TypeName(FilesToOpen) = "Boolean" Then
MsgBox "No Files were selected"
GoTo ExitHandler
End If
x = 1
Set wkbTemp = Workbooks.Open(FileName:=FilesToOpen(x))
wkbTemp.Sheets(1).Copy
Set wkbAll = ActiveWorkbook
wkbTemp.Close (False)
wkbAll.Worksheets(x).Columns("A:A").TextToColumns _
Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, _
ConsecutiveDelimiter:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, OtherChar:=","
x = x + 1
While x <= UBound(FilesToOpen)
Set wkbTemp = Workbooks.Open(FileName:=FilesToOpen(x))
With wkbAll
wkbTemp.Sheets(1).Move After:=.Sheets(.Sheets.Count)
.Worksheets(x).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
End With
x = x + 1
Wend
wkbAll.Sheets.Copy After:=Workbooks(2).Sheets(Workbooks(2).Worksheets.Count)
wkbAll.Close False
ExitHandler:
Application.ScreenUpdating = True
Set wkbAll = Nothing
Set wkbTemp = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description
Resume ExitHandler
End Sub
Function Select_File_Or_Files_Mac() As String()
Dim MyPath As String
Dim MyScript As String
Dim MyFiles As String
Dim MySplit As Variant
Dim N As Long
Dim FName As String
Dim mybook As Workbook
On Error Resume Next
MyPath = MacScript("return (path to documents folder) as String")
'Or use MyPath = "Macintosh HD:Users:Ron:Desktop:TestFolder:"
' In the following statement, change true to false in the line "multiple
' selections allowed true" if you do not want to be able to select more
' than one file. Additionally, if you want to filter for multiple files, change
' {""com.microsoft.Excel.xls""} to
' {""com.microsoft.excel.xls"",""public.comma-separated-values-text""}
' if you want to filter on xls and csv files, for example.
MyScript = _
"set applescript's text item delimiters to "","" " & vbNewLine & _
"set theFiles to (choose file of type " & _
" {""com.microsoft.excel.xls"",""public.comma-separated-values-text"", ""public.text""} " & _
"with prompt ""Please select a file or files"" default location alias """ & _
MyPath & """ multiple selections allowed true) as string" & vbNewLine & _
"set applescript's text item delimiters to """" " & vbNewLine & _
"return theFiles"
MyFiles = MacScript(MyScript)
Dim returnList() As String
On Error GoTo 0
If MyFiles <> "" Then
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
'MsgBox MyFiles
MySplit = Split(MyFiles, ",")
ReDim returnList(LBound(MySplit) To UBound(MySplit))
For N = LBound(MySplit) To UBound(MySplit)
returnList(N) = MySplit(N)
Next N
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
Select_File_Or_Files_Mac = returnList
Else
ReDim returnList(0 To 0)
returnList(0) = "False"
Select_File_Or_Files_Mac = returnList
End If
End Function
Both Application.GetOpenFilename and Select_File_Or_Files_Mac return an array of one or more file names, but the first array is one-based, and your Mac version is zero-based.
Your counter x starts at 1, so it's already out of range for a "mac" array with only one file: i.e. FilesToOpen(0)
You can modify your Mac code to return a one-based array.
Modify this part:
MySplit = Split(MyFiles, ",")
ReDim returnList(1 to To UBound(MySplit)+1) 'one-based not zero-based...
For N = LBound(MySplit) To UBound(MySplit)
returnList(N + 1) = MySplit(N)
Next N
...and this part:
ReDim returnList(1 To 1)
returnList(1) = "False"

VBA - Run time Error '91' Object variable or with block variable not set

I have created a file which I run multiple macros (for example 5). Everything works when I run all macros and I shared the file to a colleague (A) who said it works good. But when colleague (A) share to colleague (B), they encountered this error.
Can you please guide me on where I have been wrong?
Sub CaseListing()
Dim wbSource As Workbook, lastRow As Long
Application.ScreenUpdating = False
ThisWorkbook.Sheets("SR - Information").Range("A2:B1048576").Clear
Set wbSource = Workbooks.Open(Filename:="https://*/All_Region_Case_List_CURRENT.xlsx", UpdateLinks:=False, ReadOnly:=True)
lastRow = wbSource.Sheets("Sheet1").Range("B" & Rows.Count).End(xlUp).Row
wbSource.Activate
Range("B4:B" & lastRow & ",K4:K" & lastRow).Copy ThisWorkbook.Sheets("SR - Information").Range("A2")
wbSource.Close
With ThisWorkbook.Sheets("SR - Information").Range("A1:A" & Range("A" & Rows.Count).End(xlDown).Row)
.NumberFormat = "General"
.Value = .Value
End With
ThisWorkbook.Sheets("SR - Information").Range("E1") = "<-- last refreshed on " & Now()
Application.ScreenUpdating = True
End Sub
EMAIL
Public wsSR As Worksheet
Sub CreateEmail()
Dim TempFilePath As String, TempFileName As String, FileExtStr As String, myFile As String
Dim LastCell As Long, endR As Long
Dim Fname As String, Lname As String, EmailAddress As String
Dim ol As Outlook.Application
Dim mi As Outlook.MailItem
Dim c1, c2 As Collection, msg As String, i As Variant
Set wbMe = ThisWorkbook
Set wsBW = wbMe.Sheets("B+W")
Set wsSR = wbMe.Sheets("SR - Information")
Set wsFinal = wbMe.Sheets("Report")
Set wsCNA = ThisWorkbook.Sheets("C+N ")
Set wsWebCNA = ThisWorkbook.Sheets("Web")
Set c1 = New Collection
Set c2 = New Collection
pwd = "abc"
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
wsFinal.Unprotect pwd
'Clear and Copy to the Final sheet
wsFinal.Range("A5:V1048576").Clear
LastCell = wsBW.Range("A" & Rows.Count).End(xlUp).Row
wsBW.Range("A4:V" & LastCell).Copy
wsFinal.Range("A4").PasteSpecial Paste:=xlPasteValues
Set wsSR = ThisWorkbook.Sheets("SR - Information")
endR = wsSR.Range("Q" & Rows.Count).End(xlUp).Row
wsSR.Visible = False
wsBW.Visible = False
wsCNA.Visible = False
wsWebCNA.Visible = False
wsFinal.Range("A4:V" & Cells(Rows.Count, 1).End(xlUp).Row).Columns.AutoFit
Set ol = New Outlook.Application
Set mi = ol.CreateItem(olMailItem)
For Each cel In Sheets("SR - Information").Range("Q2:Q" & endR).Cells
wsFinal.Activate
wsFinal.Unprotect pwd
Range("A4:V" & Cells(Rows.Count, 22).End(xlUp).Row).AutoFilter Field:=22, Criteria1:=cel ', visibledropdown:=False
Set IndxLookupRange = Sheets("SR - Information").Range("H:I")
Set Matchlookuprange = Sheets("SR - Information").Range("H:H")
cel.Offset(0, 1) = Application.WorksheetFunction.IfError(Application.Index(IndxLookupRange, Application.Match(cel, Matchlookuprange, 0), 2), "-")
EmailAddress = cel.Offset(0, 1)
'Temporary file details
TempFilePath = Environ$("temp") & "\"
TempFileName = " Report - " & Format(Now, "mmmm dd, yyyy")
FileExtStr = "." & LCase(Right(ThisWorkbook.Name, Len(ThisWorkbook.Name) - InStrRev(ThisWorkbook.Name, ".", , 1)))
If EmailAddress <> "-" Then
For Each oAccount In ol.Session.Accounts
If oAccount = "pqrs.abc#xyz.com" Then 'BD_Best_Practice
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
'Get the file ready - protection and hide
wsBW.protect pwd
wbMe.protect Password:=pwd, Structure:=True, Windows:=True
'Keep the desired sheet activate and save as temp file
wsFinal.Activate
wsFinal.protect pwd
wbMe.SaveCopyAs TempFilePath & TempFileName & FileExtStr
On Error Resume Next
With OutMail
.To = EmailAddress
.CC = ""
.BCC = ""
.Subject = " Report" '& Format(Now, "mmmm dd, yyyy") '" & Fname & "," & "<br> <br> "
.HTMLBody = "<BODY style='font-family:Calibri; font-size:11pt';>Hi, <br><br>" & _
"Please find the attached the Report. This report shows your Plan Sponsor's Enhanced Access user activity." & _
"<br> <br> Thank you, <br> xyz" & Range("F3") & "</font></BODY>"
.Attachments.Add TempFilePath & TempFileName & FileExtStr
Set .SendUsingAccount = oAccount
'.Display
.send
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End If
Next oAccount
'Delete the temp file
Kill TempFilePath & TempFileName & FileExtStr
Else
c1.Add cel, CStr(cel)
c2.Add cel, CStr(cel)
End If
Next cel
wbMe.Unprotect Password:=pwd
wsBW.Visible = True
wsSR.Visible = True
wsCNA.Visible = True
wsWebCNA.Visible = True
If c1.Count = 0 Then
msg = "All Service Reps are matched!"
Range("Q:R").Clear
MsgBox msg
Exit Sub
Else
msg = "Make sure to update the below list of Service Reps information manually!" & vbCrLf
For i = 1 To c1.Count
msg = msg & vbCrLf & c1.Item(i)
Next i
End If
MsgBox msg '& vbCrLf & vbCrLf & "Make sure Service Reps Details are updated manually!"
wsSR.Range("Q:R").Clear
wsBW.Select
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
IMPORTFILES
Public wbMe As Workbook
Public wsBW As Worksheet, wsSR As Worksheet, wsFinal As Worksheet
Public wsBoxi As Worksheet, wsWeb As Worksheet, wsWebCNA As Worksheet, wsNDR As Worksheet
Public pwd As Variant, domain As String
Public wsCNA As Worksheet
Sub ImportFiles()
'PURPOSE: 1 B and 1 W
Dim f, fpath As String
If MsgBox("Is it 2 B and 1 W?", vbYesNo) = vbNo Then
Set wbMe = ThisWorkbook
Set wsBW = wbMe.Sheets("B+W")
Set wsSR = wbMe.Sheets("SR - Information")
Set wsFinal = wbMe.Sheets("Report")
pwd = "abc"
Application.ScreenUpdating = False
wsBW.Unprotect pwd
If wsBW.AutoFilterMode = True Then wsBW.AutoFilterMode = False
wsBW.Range("A4:Y1048576").Clear
wbMe.Unprotect Password:=pwd ', Structure:=False, Windows:=False
wsSR.Visible = True
wsSR.Columns("P:R").Clear
P = wbMe.Sheets.Count
For m = P To 1 Step -1
t = wbMe.Sheets(m).Name
If t <> "B+W" And t <> "SR - Information" And t <> "Report" And t <> "C+ " And t <> "Web" And t <> "NDRs" Then
Application.DisplayAlerts = False
wbMe.Sheets(m).Delete
Application.DisplayAlerts = True
End If
Next m
fpath = GetFolder & "\"
Application.ScreenUpdating = False
If fpath = "\" Then
Exit Sub
Else
f = Dir(fpath)
Do While Len(f) > 0
Select Case Right(f, Len(f) - InStrRev(f, "."))
Case "xls", "xlsx", "csv"
OpenFile (fpath & f)
End Select
f = Dir
Loop
Set wsBoxi = wbMe.Sheets("Sheet1")
Set wsWeb = wbMe.Sheets("GBA Access IDS")
Call Merger
Call Reorder_Columns
'Apply Formats
wsWeb.Range("A1").Copy
wsBW.Range("A4:W4").PasteSpecial xlFormats
wsBW.Rows("4:4").Columns.AutoFit
Application.CutCopyMode = False
Range("A4").Select
P = wbMe.Sheets.Count
For m = P To 1 Step -1
t = wbMe.Sheets(m).Name
If t <> "BOXI+WEB" And t <> "SR - Information" And t <> "Report" And t <> "C+N " And t <> "Web" And t <> "NDRs" Then
Application.DisplayAlerts = False
wbMe.Sheets(m).Delete
Application.DisplayAlerts = True
End If
Next m
wsBW.Range("$A$4:$U$1048576").AutoFilter Field:=1, Criteria1:="C ", Operator:=xlOr, Criteria2:="N "
MsgBox "Merge Successful!"
Application.ScreenUpdating = True
End If
Else
Call LoopAllFilesInFolder
End If
End Sub
Function GetFolder() As String
Dim f As String
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select multiple Files"
.AllowMultiSelect = False
.InitialFileName = ThisWorkbook.Path
If .Show <> -1 Then GoTo There
f = .SelectedItems(1)
End With
There:
GetFolder = f
End Function
Private Sub OpenFile(filepath)
Dim sh, wb As Workbook
Set wb = Workbooks.Open(filepath)
'Debug.Print filepath
For Each sh In wb.Sheets
sh.Copy After:=wbMe.Sheets(wbMe.Sheets.Count)
Next sh
wb.Close False
End Sub
Private Sub Merger()
Dim lastRow As Long
wsBoxi.Rows("2:2").EntireRow.Delete
wsWeb.Rows("1:2").EntireRow.Delete
'Reorder BOXI columns
wsBoxi.Columns("D:D").Cut
wsBoxi.Columns("A:A").Insert Shift:=xlToRight
Set IndexRange = wsBoxi.Range("A:G") 'BOXI
Set MatchLookupRng = wsBoxi.Range("A:A")
lastRow = wsWeb.Range("A" & Rows.Count).End(xlUp).Row
wsWeb.Activate
For Each AdID In wsWeb.Range("E2:E" & lastRow).Cells
Range("P" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 2), "-") 'Market Segment
Range("Q" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 3), "-") 'Region code
Range("R" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 4), "-") 'Cleint#
Range("S" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 5), "-") 'Admin Access Level
Range("T" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 6), "-") 'Admin Location Access
Range("U" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 7), "-") 'Admin Access to all Locations
Next AdID
wsWeb.Range("P1").Value = "Market Segment"
wsWeb.Range("Q1").Value = "Region Code"
wsWeb.Range("R1").Value = "Client#"
wsWeb.Range("S1").Value = "Admin Access Level"
wsWeb.Range("T1").Value = "Admin Location Access"
wsWeb.Range("U1").Value = "Admin Access to all Locations"
wsWeb.Range("A1:U" & lastRow).Copy wsBW.Range("A4")
wsBW.Range("A4:Y1048576").Font.Name = "Calibri"
wsBW.Range("A4:Y1048576").Font.Size = 10
End Sub
Private Sub Reorder_Columns() 'Final Columns
Dim ColumnOrder As Variant, ndx As Integer
Dim Found As Range, counter As Integer
ColumnOrder = Array("Market Segment", "Region Code", "Requestor Access ID", "Requestor Email", "Client#", "Transaction Type", _
"Date Processed", "Admin First Name", "Admin Last Name", "Admin Language", "Admin Email", "Admin Access ID", "Admin Access Level", _
"Admin Location Access", "Admin Access to all Locations", "Changed Admin First Name", "Changed Admin Last Name", "Changed Admin Language", _
"Changed Admin Email", "Changed Admin Access Level", "Changed Admin Location Access")
counter = 1
wsBW.Activate
For ndx = LBound(ColumnOrder) To UBound(ColumnOrder)
Set Found = Rows("4:4").Find(ColumnOrder(ndx), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)
If Not Found Is Nothing Then
If Found.Column <> counter Then
Found.EntireColumn.Cut
Columns(counter).Insert Shift:=xlToRight
Application.CutCopyMode = False
End If
counter = counter + 1
End If
Next ndx
Call HighlightPlanAdmin
End Sub
Private Sub HighlightPlanAdmin()
Dim ReqID As Range, nReqID As String, rReqID As String, tType As String, ntType As String
wsBW.Activate
For Each ReqID In Range("C5:C" & Cells(Rows.Count, 1).End(xlUp).Row).Cells
rReqID = Trim(ReqID)
tType = Trim(ReqID.Offset(0, 3)) '"Add Plan Admin"
If tType = "Add Plan Admin" Then
nReqID = Trim(ReqID.Offset(1, 0)) 'Requestor ID next row
If rReqID = nReqID Then
ntType = Trim(ReqID.Offset(1, 3))
If ntType <> "Add Plan Admin to OASIS." Then
ReqID.Offset(0, 3).Font.ColorIndex = 3
End If
Else
ReqID.Offset(0, 3).Font.ColorIndex = 3
End If
If nReqID = "" Then
ntType = Trim(ReqID.Offset(1, 3))
If ntType = "" Then
ReqID.Offset(0, 3).Font.ColorIndex = 3
End If
End If
End If
Next ReqID
End Sub
Sub LoopAllFilesInFolder()
'PURPOSE: 2 B and 1 W. To loop through all Excel files in a user specified folder and perform ...
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set wsBW = ThisWorkbook.Sheets("B+W")
Set wsCNA = ThisWorkbook.Sheets("C+N ")
Set wsWebCNA = ThisWorkbook.Sheets("Web")
Set wsFinal = ThisWorkbook.Sheets("Report")
Set wsSR = ThisWorkbook.Sheets("SR - Information")
wsBW.Unprotect "abc"
If wsBW.AutoFilterMode = True Then wsBW.AutoFilterMode = False
wsSR.Range("Q1:R1048576").Clear
wsBW.Range("A4:Y1048576").Clear
wsCNA.Range("A1:G1048576").Clear
wsWebCNA.Range("A1:Z1048576").Clear
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & "\"
.Title = "Select A Target Folder"
.Show
If .SelectedItems.Count <> 0 Then
xDirect = .SelectedItems(1) & "\"
xFname = Dir(xDirect, 7)
Do While xFname <> ""
If InStr(1, xFname, "C ", vbTextCompare) <> 0 Then
Set wb = Workbooks.Open(Filename:=xDirect & xFname)
dendRow = wsCNA.UsedRange.Rows.Count
wb.Worksheets(1).UsedRange.Copy
If dendRow = 1 Then
wsCNA.Range("A" & dendRow).PasteSpecial Paste:=xlPasteValues
Else
wsCNA.Range("A" & dendRow + 1).PasteSpecial Paste:=xlPasteValues
End If
wb.Close
ElseIf InStr(1, xFname, "N ", vbTextCompare) <> 0 Then
Set wb = Workbooks.Open(Filename:=xDirect & xFname)
dendRow = wsCNA.UsedRange.Rows.Count
wb.Worksheets(1).UsedRange.Copy
wsCNA.Range("A" & dendRow + 1).PasteSpecial Paste:=xlPasteValues
wb.Close
ElseIf InStr(1, xFname, "Web", vbTextCompare) <> 0 Then
Set wb = Workbooks.Open(Filename:=xDirect & xFname)
wb.Worksheets(1).UsedRange.Copy
wsWebCNA.Range("A1").PasteSpecial Paste:=xlPasteValues
wb.Close
End If
xFname = Dir
Loop
End If
End With
wsCNA.Activate
For Each cel In wsCNA.Range("A3:A" & Range("A" & Rows.Count).End(xlUp).Row).Cells
If InStr(1, cel, "Market Segment", vbTextCompare) <> 0 Then
cel.Offset(1, 0).EntireRow.Delete
cel.EntireRow.Delete
End If
Next cel
Call MergerFolder
Call Reorder_Columns_Folder
'Apply Formats
wsBW.Range("A4:W4").Font.Bold = True
wsBW.Range("A4:W4").Font.Underline = xlUnderlineStyleSingle
wsBW.Rows("4:4").Columns.AutoFit
Application.CutCopyMode = False
Range("A4").Select
wsBW.Range("$A$4:$U$1048576").AutoFilter Field:=1, Criteria1:="Corporate Accounts", Operator:=xlOr, Criteria2:="N "
MsgBox "Merge Successful!"
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Private Sub MergerFolder()
Dim lastRow As Long
wsCNA.Rows("2:2").EntireRow.Delete
wsWebCNA.Rows("1:2").EntireRow.Delete
'Reorder BOXI columns
wsCNA.Columns("D:D").Cut
wsCNA.Columns("A:A").Insert Shift:=xlToRight
Set IndexRange = wsCNA.Range("A:G") 'BOXI
Set MatchLookupRng = wsCNA.Range("A:A")
lastRow = wsWebCNA.Range("A" & Rows.Count).End(xlUp).Row
wsWebCNA.Activate
For Each AdID In wsWebCNA.Range("E2:E" & lastRow).Cells
Range("P" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 2), "-") 'Market Segment
Range("Q" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 3), "-") 'Region code
Range("R" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 4), "-") 'Cleint#
Range("S" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 5), "-") 'Admin Access Level
Range("T" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 6), "-") 'Admin Location Access
Range("U" & AdID.Row).Value = Application.IfError(Application.Index(IndexRange, Application.Match(AdID, MatchLookupRng, 0), 7), "-") 'Admin Access to all Locations
Next AdID
wsWebCNA.Range("P1").Value = "Market Segment"
wsWebCNA.Range("Q1").Value = "Region Code"
wsWebCNA.Range("R1").Value = "Client#"
wsWebCNA.Range("S1").Value = "Admin Access Level"
wsWebCNA.Range("T1").Value = "Admin Location Access"
wsWebCNA.Range("U1").Value = "Admin Access to all Locations"
wsWebCNA.Range("A1:U" & lastRow).Copy wsBW.Range("A4")
wsBW.Range("A4:Y1048576").Font.Name = "Calibri"
wsBW.Range("A4:Y1048576").Font.Size = 10
End Sub
Private Sub Reorder_Columns_Folder() 'Final Columns
Dim ColumnOrder As Variant, ndx As Integer
Dim Found As Range, counter As Integer
ColumnOrder = Array("Market Segment", "Region Code", "Requestor Access ID", "Requestor Email", "Client#", "Transaction Type", _
"Date Processed", "Admin First Name", "Admin Last Name", "Admin Language", "Admin Email", "Admin Access ID", "Admin Access Level", _
"Admin Location Access", "Admin Access to all Locations", "Changed Admin First Name", "Changed Admin Last Name", "Changed Admin Language", _
"Changed Admin Email", "Changed Admin Access Level", "Changed Admin Location Access")
counter = 1
wsBW.Activate
For ndx = LBound(ColumnOrder) To UBound(ColumnOrder)
Set Found = Rows("4:4").Find(ColumnOrder(ndx), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)
If Not Found Is Nothing Then
If Found.Column <> counter Then
Found.EntireColumn.Cut
Columns(counter).Insert Shift:=xlToRight
Application.CutCopyMode = False
End If
counter = counter + 1
End If
Next ndx
Call HighlightPlanAdmin_Folder
End Sub
Private Sub HighlightPlanAdmin_Folder()
Dim ReqID As Range, nReqID As String, rReqID As String, tType As String, ntType As String
wsBW.Activate
For Each ReqID In Range("C5:C" & Cells(Rows.Count, 1).End(xlUp).Row).Cells
ReqID.Select
rReqID = Trim(ReqID)
tType = Trim(ReqID.Offset(0, 3)) '"Add Plan Admin"
If tType = "Add Plan Admin" Then
nReqID = Trim(ReqID.Offset(1, 0)) 'Requestor ID next row
If rReqID = nReqID Then
ntType = Trim(ReqID.Offset(1, 3))
If ntType <> "Add Plan Admin to OASIS." Then
ReqID.Offset(0, 3).Font.ColorIndex = 3
End If
Else
ReqID.Offset(0, 3).Font.ColorIndex = 3
End If
If nReqID = "" Then
ntType = Trim(ReqID.Offset(1, 3))
If ntType = "" Then
ReqID.Offset(0, 3).Font.ColorIndex = 3
End If
End If
End If
Next ReqID
End Sub
SRMATCH
Public wsSR As Worksheet
Sub ServiceRepMatch()
Set wsSR = ThisWorkbook.Sheets("SR - Information")
Set wsBW = ThisWorkbook.Sheets("B+W")
Set SRLookupRng = wsSR.Range("A:B")
Set macth = wsSR.Range("B1:B1048576")
Application.ScreenUpdating = False
wsBW.Range("V4").Value = "Service Reps"
For Each cel In wsBW.Range("E5:E" & Cells(Rows.Count, 1).End(xlUp).Row).Cells
cel.Offset(0, 17) = Application.IfError(Application.VLookup(cel, SRLookupRng, 2, 0), "-")
Next cel
wsBW.Range("V4:V" & Cells(Rows.Count, 22).End(xlUp).Row).Copy wsSR.Range("P1")
wsSR.Select
wsSR.Range("P1:P" & Cells(Rows.Count, 16).End(xlUp).Row).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=wsSR.Range("Q1"), Unique:=True
wsSR.Columns("P").Clear
wsBW.Select
MsgBox "DONE!"
Application.ScreenUpdating = True
End Sub
In nutshell, we first run IMPORTFILES to merge 2 reports it can either be 2 or 3 and perform some data manipluations. Secondly, CASELISTING is used to get the SR's client#. Third, we match the respective sales representatives through SRMATCH. Last, we use CREATEEMAIL to send individual emails for SR's their report and confidently message in the Body.

Why am I getting a type mismatch on this MyCell range error?

I keep getting a runtime error on this line:
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=MgrPath & "2018 Mid-Year Comp Statement - " & SM.Range("C5").Value & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Sub Statement_Autoprint()
Dim MCST As Workbook: Set MCST = ActiveWorkbook
Dim User As String: User = Environ$("Username")
Dim SavePath As String: SavePath = "M:\comp_statements\"
Dim CS As Worksheet: Set CS = MCST.Sheets("Control Sheet")
Dim MgrPath As String, MyCell As Range, Printed As Integer, i As Integer, SM As Worksheet
Printed = 0
Call Disable
For i = 2 To CS.Range("B" & CS.Rows.Count).End(xlUp).Row
If CS.Range("A" & i) <> "" & CS.Range("B" & i) <> "" Then
Set SM = MCST.Sheets(CStr(CS.Range("A" & i)))
SM.Calculate
SM.Range("P1") = Format(CS.Range("B" & i), "000000000")
For Each MyCell In SM.Range("N2:N70")
If MyCell = "HIDE" Then
MyCell.EntireRow.Hidden = True
ElseIf MyCell <> "HIDE" Then
MyCell.EntireRow.Hidden = False
End If
Next MyCell
If Not Application.CalculationState = xlDone Then
DoEvents
End If
MgrPath = "M:\Pittsburgh\GRP4\HR_PCorpComp\2018 Midyear\Reporting\Parsley\comp_statements\" & SM.Range("K5") & "\"
If Dir(MgrPath, vbDirectory) <> "" Then
MkDir MgrPath
End If
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=MgrPath & "2018 Mid-Year Comp Statement - " & SM.Range("C5").Value & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Printed = Printed + 1
End If
Next i
CS.Activate
Call Re_Enable
End Sub
I do not have any files that exist/are open under that name, I have no clue what could be preventing this from saving. All of the other bits of code do what they're supposed to, it just can't loop to the next employee because the save is being suppressed because of that error.
Try this
For Each mycell In SM.Range("N2:N70")
If IsError(mycell) Then
Debug.Print mycell.Address
Else
mycell.EntireRow.Hidden = (mycell = "HIDE")
End If
Next mycell
Either handle the error using IsError or
Go to the cell which the above code points to and check if there are any formula errors.
You usually get that error if the cell has formula errors.

2 Macros 1 Module

Hello I have these two macros in one module but when I run it only runs the first part where it deletes the rows but I would like it to also send the emails... I had some excellent help from #Simoco on the send part earlier but cant seem to figure out the combine part...
I tried to add the Call Sub... but no luck
Sorry about the length of the code...
Sub DeleteDuplicateRows()
Dim R As Long
Dim N As Long
Dim V As Variant
Dim rng As Range
Range("D2").Select
ActiveCell.FormulaR1C1 = "1"
Range("D2").Select
Selection.Copy
Range("A5").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlMultiply, _
SkipBlanks:=False, Transpose:=False
Rows("1:3").Select
Application.CutCopyMode = False
Selection.Delete Shift:=xlUp
Columns("A:A").Select
Columns("A:A").EntireColumn.AutoFit
On Error GoTo EndMacro
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Set rng = Application.Intersect(ActiveSheet.UsedRange, _
ActiveSheet.Columns(ActiveCell.Column))
Application.StatusBar = "Processing Row: " & Format(rng.Row, "#,##0")
N = 0
For R = rng.Rows.Count To 2 Step -1
If R Mod 500 = 0 Then
Application.StatusBar = "Processing Row: " & Format(R, "#,##0")
End If
V = rng.Cells(R, 1).Value
If V = vbNullString Then
If Application.WorksheetFunction.CountIf(rng.Columns(1), vbNullString) > 1 Then
rng.Rows(R).EntireRow.Delete
N = N + 1
End If
Else
If Application.WorksheetFunction.CountIf(rng.Columns(1), V) > 1 Then
rng.Rows(R).EntireRow.Delete
N = N + 1
End If
End If
Next R
EndMacro:
Application.StatusBar = False
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
MsgBox "Duplicate Rows Deleted: " & CStr(N)
End Sub
Sub Send_Email()
Dim OutApp As Object
Dim OutMail As Object
Dim strbody As String
Dim cel As Range
Dim SigString As String
Dim Signature As String
Dim lastrow As Long
Set OutApp = CreateObject("Outlook.Application")
SigString = Environ("appdata") & _
"\Microsoft\Signatures\GBS.txt"
If Dir(SigString) <> "" Then
Signature = GetBoiler(SigString)
Else
Signature = ""
End If
lastrow = Cells(Rows.Count, 3).End(xlUp).Row
For Each cel In Range("C2:C" & lastrow)
strbody = "Hi there" & cel.Offset(, -1) & vbNewLine & vbNewLine & _
"My name Is William, Please choose the following option ..." & vbNewLine & _
cel.Offset(, 3) & _
"I work at Fair" & vbNewLine & _
"Bye" & vbNewLine & _
"WH"
On Error Resume Next
With OutApp.CreateItem(0)
If cel.Value <> "" Then
.To = cel.Value
.CC = cel.Offset(0, 10).Value
.Body = strbody & vbNewLine & vbNewLine & Signature
Else
.To = cel.Offset(0, 10).Value
.Body = "Hello " & cel.Offset(, 9) & "! " & cel.Offset(, -1) & " is having this event" & vbNewLine & Signature
'.HTMLBody = strbody & vbNewLine & RangetoHTML(cel.Offset(, -2).Resize(, 4)) & vbNewLine & Signature
End If
'.BCC = ""
.Subject = "Choose your plan"
.Display
'.Attachments.Add ("C:\test.txt")
'.Send
End With
On Error GoTo 0
Next cel
Set OutApp = Nothing
End Sub
Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2013
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.readall
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")
'Close TempWB
TempWB.Close savechanges:=False
'Delete the htm file we used in this function
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
Function GetBoiler(ByVal sFile As String) As String
'**** Kusleika
Dim fso As Object
Dim ts As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)
GetBoiler = ts.readall
ts.Close
End Function
If you execute a macro you call one procedure or one function. I assume you want to call Delete_Duplicate_Rows and Send_Email. To execute two procedures you can create one procedure that calls the other procedures
Sub Delete_And_Send()
Call Delete_Duplicate_Rows()
Call Send_Email()
End Sub

List of all files in Folder / Sub Folder with Hyperlink

I am using this code to list out files in folder and sub-folder. The code is working fine. But if there is no sub-folder I get an error in the below line.
'Files under current dir
fname = Dir(fPath & "*." & fType).
And I want message-box option (Yes/no) for empty folders. (Currently its showing all empty folders)
Public oldNR As Long
Sub HyperlinkDirectory()
Dim fPath As String
Dim fType As String
Dim fname As String
Dim NR As Long
Dim AddLinks As Boolean
'Select folder
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.InitialFileName = "C:\2009\"
.Show
If .SelectedItems.Count > 0 Then
fPath = .SelectedItems(1) & "\"
Else
Exit Sub
End If
End With
'Types of files
fType = Application.InputBox("What kind of files? Type the file extension to collect" _
& vbLf & vbLf & "(Example: xls, doc, txt, pdf, *)", "File Type", "PDF", Type:=2)
If fType = "False" Then Exit Sub
'Option to create hyperlinks
AddLinks = MsgBox("Add hyperlinks to the file listing?", vbYesNo) = vbYes
'Create report
Application.ScreenUpdating = False
NR = 4
With ActiveSheet
.Range("A:C").Clear
.[A2] = "LIST OF FILES"
.[B2] = "Modified Date"
Call FindFilesAndAddLinks(fPath, fType, NR, AddLinks)
End With
With ActiveSheet
.Range("A:B").Columns.AutoFit
.Range("B:B").HorizontalAlignment = xlCenter
Range("B:B").Select
Selection.NumberFormat = "d-mmm-yy h:mm AM/pm"
End With
With ActiveSheet
Range("A2").Select
Selection.Font.Bold = True
Range("B2").Select
Selection.Font.Bold = True
Columns("A:A").Select
Selection.Font.Underline = xlUnderlineStyleNone
End With
Application.ScreenUpdating = True
End Sub
Private Sub FindFilesAndAddLinks(fPath As String, fType As String, ByRef NR As Long, AddLinks As Boolean)
Dim fname As String
Dim oFS As New FileSystemObject
Dim oDir
'Files under current dir
fname = Dir(fPath & "*." & fType)
With ActiveSheet
'Write folder name
.Range("A" & NR) = fPath
.Range("A" & NR).Select
If AddLinks Then .Hyperlinks.Add Anchor:=Selection, _
Address:=fPath, _
TextToDisplay:="FOLDER NAME: " & " " & UCase(Split(fPath, "\")(UBound(Split(fPath, "\")) - 1))
Selection.Font.Bold = True
Selection.Font.Size = 10
Selection.Font.Name = "Arial"
Selection.Font.Underline = xlUnderlineStyleNone
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent3
.TintAndShade = 0.399975585192419
.PatternTintAndShade = 0
End With
With Selection.Font
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
End With
NR = NR + 2
Do While Len(fname) > 0
'filename
If .Range("A" & NR) <> "" Then Debug.Print "Overwriting " & NR
.Range("A" & NR) = fname
'modified
.Range("B" & NR) = FileDateTime(fPath & fname)
'hyperlink
.Range("A" & NR).Select
If AddLinks Then .Hyperlinks.Add Anchor:=Selection, _
Address:=fPath & fname, _
TextToDisplay:=fname
'set for next entry
NR = NR + 1
fname = Dir
Loop
'Files under sub dir
Set oDir = oFS.GetFolder(fPath)
For Each oSub In oDir.SubFolders
NR = NR + 1
Call FindFilesAndAddLinks(oSub.Path & "\", fType, NR, AddLinks)
Next oSub
End With
ActiveWindow.DisplayGridlines = False
End Sub