I have this vba macro that extracts data from a text file and puts it into a column in Excel. The files are named by days (2016mmdd). Currently, I run this macro for each day. Now I want it such that when this Macro is run, the data for all the days in the declared month (say August) will be automatically extracted into different columns (a column per each day of the month). So that I won't have to manually run it 31 times if there are 31 days in the month. Thanks for helping.
Sub Macro7()
'
' Macro7 Macro
'
' Keyboard Shortcut: Ctrl+x
'
Dim fileDate, rng, rng1, rng2, rng3, rcell As String
b = InputBox("Enter file Name mmdd", "File name")
rcell = InputBox("Enter cell reference", "Reference name")
rng = "$" & rcell & "$2"
rng1 = rcell & "2:" & rcell & "14"
rng2 = rcell & "52:" & rcell & "62"
rng3 = rcell & "2:" & rcell & "101"
Filename = "j:\files\2016" & b & "2259.txt"
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;j:\files2016" & b & "2259.txt", Destination:= _
Range(rng))
.Name = "tr" & b
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlFixedWidth
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(9, 1, 9)
.TextFileFixedColumnWidths = Array(103, 4)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Range(rng1).Select
Selection.Delete Shift:=xlUp
ActiveWindow.SmallScroll Down:=45
Range(rng2).Select
Selection.Delete Shift:=xlUp
ActiveWindow.SmallScroll Down:=-60
Range(rng3).Select
End Sub
The quick approach would be to re-write Sub Macro7() to accept parameters, e.g.
Sub ImportFiles(FName As String, ColNum As Integer)
' blablabla
' work with range objects ... not with patched strings containing range addresses
Dim Rng As Range, Rng1 As Range, Rng2 As Range, Rng3 As Range
Set Rng = Cells(2, ColNum)
Set Rng1 = Range(Cells(2, ColNum), Cells(14, ColNum))
Set Rng2 = Range(Cells(52, ColNum), Cells(62, ColNum))
Set Rng3 = Range(Cells(2, ColNum), Cells(101, ColNum))
Filename = "j:\files\2016" & FName & "2259.txt"
' and replace <Destination := Range(Rng)> by <Destination := Rng>
' blablabla
' use the range objects defined/set earlier ... save on Select/Selection
Rng1.Delete xlUp
Rng2.Delete xlUp
Rng3.Select
End Sub
and have a calling Macro e.g.
Sub DoWorklist()
ImportFiles "0901", 1
ImportFiles "0902", 2
ImportFiles "0903", 3
' blablabla
'alternative
Dim Idx As Integer
For Idx = 1 To 30
' to overcome well spotted chr() issue we convert running number Idx
' into 2 digit string with leading "0"
ImportFiles "09" & Format(Idx, "00"), Idx
Next Idx
End Sub
Related
I have a worksheets for my projects.
the first sheet is the main one the containing all the name of the projects.
the author sheets are for every project.
in the main sheet the name of the project has hyperlink to his sheet.
when running the code I got a pop msgbox that I write the new project name (look for "project_name").
the code does stuff.
but near the end there is the hyperlink code. (look for ActiveSheet.Hyperlinks.Add....)
so my problem is:
when I choose a project name like "abcd" everything works ok. But when I choose name like "ab cd". the code runs but the hyperlink doesn't work.
I realized that having a space in the project name makes the code not work.
thanks for the help.
p.s.
The notes are in Hebrew.
Sub New_project()
'--------------------------------------------------------------------------------------------------תחילת ריצת קוד
Dim Start, Finish, TotalTime As Date
Start = Timer
'--------------------------------------------------------------------------------------------------ביטול חישובים ועדכוני מסך והתראות
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.AskToUpdateLinks = False
'--------------------------------------------------------------------------------------------------החזרת חישובים ועדכוני מסך והתראות
'Application.Calculation = xlCalculationAutomatic
'Application.ScreenUpdating = True
'Application.DisplayAlerts = True
'Application.AskToUpdateLinks = True
'--------------------------------------------------------------------------------------------------פתיחת חלונית והקלדת שם הפרויקט
'--------------------------------------------------------------------------------------------------אם לחצו cancel אז יציאה מהקוד
Dim project_name As String
project_name = InputBox("נא להקליד את שם הפרויקט החדש")
If Len(project_name) < 1 Then
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
MsgBox ("יציאה מהקוד")
Exit Sub
End If
'--------------------------------------------------------------------------------------------------בדיקה האם שם הגיליון לפרויקט החדש כבר קיים
Dim curSheet As Worksheet
Dim ArraySheets() As String
Dim x As Variant
Dim sheet_existing As Integer
x = 0
sheet_existing = 0
For Each curSheet In ActiveWorkbook.Worksheets
If curSheet.Name Like project_name Then
Worksheets(project_name).Activate
sheet_existing = 1
Finish = Timer
TotalTime = Format((Finish - Start) / 86400, "hh:mm:ss")
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
MsgBox ("שם הפרויקט כבר קיים" & vbNewLine & "זמן ריצת קוד: " & TotalTime)
Exit Sub
End If
Next curSheet
'iComp = StrComp(str1, str2, vbBinaryCompare)
'--------------------------------------------------------------------------------------------------הוספת גיליון חדש בסוף הקובץ
If sheet_existing = 0 Then
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = project_name
End If
'--------------------------------------------------------------------------------------------------הוספת כותרות
Range("A1") = "#"
Range("B1") = "תאריך"
Range("C1") = "שלב"
Range("D1") = "איש קשר"
Range("E1") = "הערות"
Range("F1") = "מסמכים"
Range("G1") = "ימים"
Range("H1") = "צבירה"
'--------------------------------------------------------------------------------------------------רוחב עמודה
Columns("A").ColumnWidth = 9
Columns("B").ColumnWidth = 11
Columns("C").ColumnWidth = 30
Columns("D").ColumnWidth = 16
Columns("E").ColumnWidth = 17
Columns("F").ColumnWidth = 9
Columns("G").ColumnWidth = 6
Columns("H").ColumnWidth = 10
'--------------------------------------------------------------------------------------------------הוספת מסגרת לתאים
Dim rng1 As Range
Set rng1 = Range(Cells(1, 1), Cells(27, 8))
With rng1.Borders
.LineStyle = xlContinuous
.Color = vbBlack
.Weight = xlThin
End With
Range("A:H").HorizontalAlignment = xlCenter
Range("A:H").VerticalAlignment = xlCenter
Rows(1).Font.Bold = True
Columns(1).Font.Bold = True
Range("A1:H1").Interior.Color = RGB(0, 176, 240)
Range("A2") = 1
Range("B2") = Date
'Range("C2") = "רשום כאן את השלב הראשון"
Range("G2") = 0
Range("H2") = 0
Range("N1:Q1").Merge
Range("N2:Q12").Merge
Range("N1:Q1").Interior.Color = RGB(0, 176, 240)
Range("N1:Q1") = "הערות"
'--------------------------------------------------------------------------------------------------הוספת מסגרת לתאים
Dim rng2 As Range
Set rng2 = Range(Cells(1, 14), Cells(12, 17))
With rng2.Borders
.LineStyle = xlContinuous
.Color = vbBlack
.Weight = xlThin
End With
Range("N:Q").HorizontalAlignment = xlCenter
Range("N:Q").VerticalAlignment = xlCenter
'--------------------------------------------------------------------------------------------------ספירת גיליונות בקובץ
Dim SheetCountA As Integer
SheetCountA = Application.Sheets.Count
'--------------------------------------------------------------------------------------------------העתקת כפתור חזרה לגיליון החדש
Sheets(SheetCountA - 1).Select
ActiveSheet.Shapes.Range(Array("Rectangle 1")).Select
Selection.Copy
Sheets(SheetCountA).Select
ActiveSheet.Paste Destination:=Worksheets(SheetCountA).Range("K1")
Sheets(SheetCountA - 1).Select
Range("B1").Copy
Sheets(SheetCountA).Select
Range("B1").PasteSpecial Paste:=xlPasteFormats
Application.CutCopyMode = False
Range("A1").Select
Sheets(SheetCountA - 1).Select
Range("A1").Select
Sheets("סיכום").Select
Dim LastRowA As Integer
LastRowA = Application.CountA(Range("B:B"))
'--------------------------------------------------------------------------------------------------הוספת מספור לפרויקט החדש
Cells(LastRowA + 1, 1) = Cells(LastRowA, 1) + 1
'--------------------------------------------------------------------------------------------------הוספת היפר-לינק
ActiveSheet.Hyperlinks.Add Anchor:=Cells(LastRowA + 1, 2), Address:="", SubAddress:= _
project_name & "!A1", TextToDisplay:=project_name
Cells(LastRowA + 1, 2).HorizontalAlignment = xlCenter
Cells(LastRowA + 1, 2).VerticalAlignment = xlCenter
Range("A1").Select
'--------------------------------------------------------------------------------------------------זמן סיום ריצת קוד וחישוב
Finish = Timer
TotalTime = Format((Finish - Start) / 86400, "hh:mm:ss")
MsgBox ("הדו''ח מוכן" & vbNewLine & "זמן ריצת קוד: " & TotalTime)
'--------------------------------------------------------------------------------------------------שאלה האם לעבור לקוד שמרענן את הקובץ
Dim answer2 As Integer
answer2 = MsgBox("?האם לרענן את הקובץ", vbYesNo + vbQuestion, "מעבר לקוד הבא")
If answer2 = vbYes Then
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
Call Refresh_file
End If
'--------------------------------------------------------------------------------------------------שמירת הקובץ
ThisWorkbook.Save
'--------------------------------------------------------------------------------------------------החזרת חישובים ועדכוני מסך והתראות
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
End Sub
To make the hyperlink valid, you just need to wrap the sheet name in quotes, so:
ActiveSheet.Hyperlinks.Add Anchor:=Cells(LastRowA + 1, 2), Address:="", SubAddress:= _
project_name & "!A1", TextToDisplay:=project_name
becomes
ActiveSheet.Hyperlinks.Add Anchor:=Cells(LastRowA + 1, 2), Address:="", SubAddress:="'" & _
project_name & "'" & "!A1", TextToDisplay:=project_name
I have some data in my excel file and based on that data I'm using a macro for generating the report which should be saved in the place specified by path provided by the user. On my laptop, with Win10 everything is working fine, but on PC there is an error when we try to generate a report. Instead of saving the report in provided place excel is asking me to save data in "Book16" as shows the screenshot below. Do I have no idea why?
Here is the code of macro responsible for creating the report:
Sub Nationalreports()
Dim sh1 As Worksheet, N As Long
Dim st As String
Dim wbUnSaved As Workbook
Dim wbSaved As Workbook
Dim RedemptiontypeIncHdgs As Range
Dim RedemptiontypeExcHdgs As Range
Dim Fr As Long, LR As Long
Dim vaFiles As Variant
Dim i As Long
Dim wbkToCopy As Workbook
Dim ws As Worksheet, strFile As String
Dim File_path As String
Dim qry As QueryTable
Dim FilNams As Variant
Dim FilNamCntr As Long
Dim strQryName As String
Dim lastrow As Long
Application.ScreenUpdating = False
If Range("E8").Value = 0 Then
MsgBox "Please Specify FilePath", vbExclamation, "Please Specify
FilePath"
Range("E8").Activate
Exit Sub
End If
File_path = Sheets("Control").Range("E8").Value
Set wbksaved = ActiveWorkbook
MsgBox "Please Select MVRT Reports", vbInformation, "Select Files"
FilNams = Application.GetOpenFilename(FileFilter:="CSV Files
(*.csv),*.csv", _
Title:="Select Textfile to
Import", _
MultiSelect:=True)
If TypeName(FilNams) = "Boolean" Then
MsgBox "No Files Selected", vbExclamation, "No Files Selected"
Exit Sub
Else
End If
For FilNamCntr = LBound(FilNams) To UBound(FilNams)
FilNams(FilNamCntr) = "TEXT;" & FilNams(FilNamCntr)
Next FilNamCntr
For FilNamCntr = LBound(FilNams) To UBound(FilNams)
Sheets("Data").Cells.NumberFormat = "#"
Set wbkToCopy = Workbooks.Add
With ActiveSheet
If .Range("A" & Rows.Count).End(xlUp).Row = 1 Then
lastrow = 1
Else
lastrow = .Range("A" & Rows.Count).End(xlUp).Row + 1
End If
Set qry = .QueryTables.Add(Connection:=FilNams(FilNamCntr), _
Destination:=.Range("A" & lastrow))
With qry
.Name = "Filename"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End With
'-------------------------------------------------------------------------------------------
'NEW CODE:
'-------------------------------------------------------------------------------------------
'progress
'Rows("1:1").Delete
'ActiveSheet.UsedRange.Columns("A:T").SpecialCells(xlCellTypeVisible).Copy
'wbksaved.Sheets("Data").Cells(Rows.Count, "A").End(xlUp).Offset(0).PasteSpecial Paste:=xlPasteValues
ActiveSheet.UsedRange.Columns("A:T").SpecialCells(xlCellTypeVisible).Select
Selection.Copy
'wbksaved.Sheets("Data").Activate
'Range("A1").Select
'ActiveSheet.Paste
wbksaved.Sheets("Data").Paste
'ERROR IS HERE ^^^^^^^^^^^^^
'-------------------------------
'new:
Application.CutCopyMode = False
'-------------------------------
Application.DisplayAlerts = False
ActiveWorkbook.Close False
Application.DisplayAlerts = True
Next FilNamCntr
Set wbkToCopy = Workbooks.Add
wbkToCopy.Sheets(1).Name = "Duplicates,Invalid"
wbkToCopy.Worksheets.Add().Name = "Breakdown"
wbkToCopy.Worksheets.Add().Name = "Summary"
wbksaved.Sheets("Redemption").UsedRange.Columns("C:D").Copy
Sheets("Duplicates,Invalid").Range("A1").PasteSpecial Paste:=xlPasteValues
'-------------------------------
'new:
Application.CutCopyMode = False
'-------------------------------
' Duplicates & Invalids Sheet
Sheets("Duplicates,Invalid").Activate
Columns("B").Cut Destination:=Columns("F")
Columns("A").Cut Destination:=Columns("B")
Range("B1").Value = "Duplicate Codes"
Range("F1").Value = "Invalid Codes"
Range("A2").Value = "1"
Range("A3").Value = "2"
On Error Resume Next
Cells(2, 1).AutoFill Destination:=Range("A2:A" & Range("B" & Rows.Count).End(xlUp).Row), Type:=xlFillSeries
Range("E2").Value = "1"
Range("E3").Value = "2"
On Error Resume Next
Cells(2, 5).AutoFill Destination:=Range("E2:E" & Range("F" & Rows.Count).End(xlUp).Row), Type:=xlFillSeries
Range("A1").Value = "Nr."
Range("E1").Value = "Nr."
Columns("A:F").EntireColumn.AutoFit
Columns("A:F").HorizontalAlignment = xlCenter
Cells.Interior.Pattern = xlSolid
Cells.Interior.TintAndShade = -0.0499893185216834
Range("A1:B1,E1:F1").Interior.ThemeColor = xlThemeColorLight1
Range("A:B,E:F").Borders.LineStyle = xlContinuous
Range("A1:B1,E1:F1").Font.ThemeColor = xlThemeColorDark1
Range("A1:B1,E1:F1").Font.Bold = True
Application.Goto Reference:=Range("A1"), Scroll:=True
' Breakdown Sheet
Sheets("Breakdown").Activate
Cells.NumberFormat = "#"
wbksaved.Sheets("MVRT").UsedRange.Columns("A:D").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "A").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("F:F").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "E").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("H:H").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "F").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("N:N").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "G").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("S:S").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "H").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("K:K").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "I").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("J:J").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "J").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("M:M").SpecialCells(xlCellTypeVisible).Copy
wbkToCopy.Sheets("Breakdown").Cells(Rows.Count, "K").End(xlUp).Offset(0).PasteSpecial xlPasteValues
wbksaved.Sheets("MVRT").UsedRange.Columns("Q:Q").SpecialCells(xlCellTypeVisible).Copy
ActiveSheet.Paste Destination:=Worksheets("Breakdown").Range("L:L")
'-------------------------------
'new:
Application.CutCopyMode = False
'-------------------------------
'Range("O:P").Delete
Range("A1").Value = "UUID"
Range("B1").Value = "Security Code"
Range("C1").Value = "Customer Code"
Range("D1").Value = "Country Code"
Range("E1").Value = "Salesforce Id"
Range("F1").Value = "Merchant Name"
Range("G1").Value = "Unit Status"
Range("H1").Value = "Redemption Status"
Range("I1").Value = "Expires At"
Range("J1").Value = "Expired"
Range("K1").Value = "Suspended"
Range("L1").Value = "Redemption Date"
'Range("M:M").Replace What:="Invalid Rights", Replacement:="Other Country"
Range("B:L").Sort Key1:=Range("I:I"), Order1:=xlAscending, Header:=xlYes
Range("A:L").EntireColumn.AutoFit
Range("A1:L1").HorizontalAlignment = xlCenter
Cells.Interior.Pattern = xlSolid
Cells.Interior.TintAndShade = -0.0499893185216834
Range("A1:L1").Interior.ThemeColor = xlThemeColorLight1
Range("A:L").Borders.LineStyle = xlContinuous
Range("A1:L1").Font.ThemeColor = xlThemeColorDark1
Rows("1:1").Font.Bold = True
Application.Goto Reference:=Range("A1"), Scroll:=True
'Summary Sheet
Sheets("Summary").Activate
Range("C9").Value = "Country"
Range("C10").Value = "Merchant Name"
Range("C11").Value = "Type"
Range("C16").Value = "Redemption Type"
Range("C17").Value = "Invalid"
Range("C18").Value = "Duplicates"
Range("C19").Value = "Suspended"
Range("C20").Value = "Voucher Expired"
Range("C21").Value = "Payment Invalid"
Range("C22").Value = "Payment Refunded"
Range("C23").Value = "Redeemed"
Range("C24").Value = "Total Codes Sent In"
Range("D9").FormulaR1C1 = "=Breakdown!R[-7]C[0]"
Range("D10").FormulaR1C1 = "=Breakdown!R[-8]C[2]"
Range("D11").FormulaR1C1 = "Offsite Redemptions"
Range("D16").FormulaR1C1 = "No."
Range("D17").FormulaR1C1 = "=COUNTA('Duplicates,Invalid'!C[2])-1"
Range("D18").FormulaR1C1 = "=COUNTA('Duplicates,Invalid'!C[-2])-1"
Range("D19").Formula = "=COUNTIFS(Breakdown!K:K,""*true*"",Breakdown!H:H,""*Forced redeemable*"")"
'Range("D19").AutoFill Destination:=Range("D19:D25"), Type:=xlFillCopy
Range("D20").Formula = "=COUNTIFS(Breakdown!J:J,""*true*"",Breakdown!K:K,""*false*"",Breakdown!G:G,""*collected*"",Breakdown!H:H,""*Forced redeemable*"")"
'payment not received:
Range("D21").Formula = "=COUNTIFS(Breakdown!K:K,""*false*"",Breakdown!G:G,""*resigned*"",Breakdown!H:H,""*Forced redeemable*"") + COUNTIFS(Breakdown!K:K,""*false*"",Breakdown!G:G,""*pending*"",Breakdown!H:H,""*Forced redeemable*"")"
'payment refunded:
Range("D22").Formula = "=COUNTIFS(Breakdown!G:G,""*deleted*"",Breakdown!K:K,""*false*"",Breakdown!H:H,""*Forced redeemable*"")"
Range("D23").Formula = "=COUNTIF(Breakdown!H:H,""*redeemed*"")"
'sum-formula:
Range("D24").Formula = "=COUNTA(Breakdown!A:A)-1 + SUM(D17:D18)"
Range("C:D").Copy
Range("C:C").PasteSpecial xlPasteValues
Application.CutCopyMode = False
Range("A:B,E:F").ColumnWidth = 26
Range("C:D").ColumnWidth = 63.29
Range("C:D").HorizontalAlignment = xlCenter
Cells.Interior.Pattern = xlSolid
Cells.Interior.TintAndShade = -0.0499893185216834
Range("C1:D5,C9:C11,C16:D16,C24:D24").Interior.ThemeColor =
xlThemeColorLight1
Range("D9:D11,C16:D24").Borders.LineStyle = xlContinuous
Range("C9:C11,C16:D16,C24:D24").Font.ThemeColor = xlThemeColorDark1
Range("C9:D11,C16:D24").Font.Bold = True
Range("C3:D3").Merge True
Dim myR As Range
Set myR = Range("C3:D3")
wbksaved.Sheets("Control").Shapes("Groupon Logo").Copy
Range("C3:D3").PasteSpecial xlPasteFormats
'-------------------------------
'new:
Application.CutCopyMode = False
'-------------------------------
Selection.ShapeRange.ScaleWidth 1, msoFalse, msoScaleFromTopLeft
Selection.ShapeRange.ScaleHeight 1, msoFalse, msoScaleFromTopLeft
Selection.ShapeRange.IncrementLeft (myR.Width - Selection.ShapeRange.Width) / 2
Application.Goto Reference:=Range("A1"), Scroll:=True
Country = Range("D9").Value
'Merchant_ID = Range("D10").Value This was DELETED on Lorene request
Merchant_Name = Range("D10").Value
dt = Format(CStr(Now), "dd_mm_yyyy_hh_mm_ss")
File_Name = File_path & "\" & "Report" & " " & Merchant_Name & " " &
Merchant_ID & " " & dt & ".xlsx"
ActiveWorkbook.SaveAs Filename:=File_Name, FileFormat:=51
ActiveWorkbook.Close
Application.DisplayAlerts = False
Sheets("Data").Cells.Delete
Application.DisplayAlerts = True
Sheets("Control").Select
MsgBox "Report Created", vbInformation, "Report Created"
Application.ScreenUpdating = True
End Sub
Can you try instead of this:
ActiveSheet.UsedRange.Columns("A:T").SpecialCells(xlCellTypeVisible).Select
Selection.Copy
wbksaved.Sheets("Data").Paste
To write this:
ActiveSheet.Columns("A:T").SpecialCells(xlCellTypeVisible).Copy
wbksaved.Sheets("Data").Range("A1").Paste
And to see whether the "error" would still exist? In general, Selection.Copy and ActiveSheet, ActiveCell should be avoided whenever possible - How to avoid using Select in Excel VBA
Hello again guys I have another tough problem for you, well may not be tough for you but it is for me. So I have one sheet with all of my data and I would like to sort by the first 3 conditions (Reject, Other, & year) Would be nice to be able to pick months too. Once the data is filtered I have it copied and sorted on another sheet so I can do some other functions and generate a table showing amount of times the vendor was rejected. There may be a simpler way to do this but currently this is the way I slapped together. If you have any other suggestions I would like to hear them.Code fails at the year sort. I keep getting all of the data from the other sheet
''Generates defect list
Sub Make_Defect_List_Yearly()
Const REJECTED_COL = 8 'Column H (DISPOSITIO)
Const DATE_COL = 13
Dim shAD As Worksheet, shVP As Worksheet
Dim adRng As Range, vpRng As Range, headers() As Variant
Dim rng As Range, cel As Range, fCell As Range, lCell As Range
Dim flg As Byte, LastRow As Long, flag As Boolean, i
Set shAD = Worksheets("AllData")
Set shVP = Worksheets("VendorProblems")
lr = shAD.Cells(Rows.Count, 1).End(xlUp).Row
Sheets("VendorProblems").UsedRange.ClearContents
'Copy VendorProblems to shVP --------------------------
Application.ScreenUpdating = False
shAD.AutoFilterMode = False
With shAD.UsedRange
Set adRng = FilterWS(.Columns(DATE_COL), "2017")
If Not adRng Is Nothing Then
If .Cells.CountLarge > 2 Then
Set vpRng = shVP.Cells(shVP.UsedRange.Rows.Count + 1, 1)
.Offset(1).Resize(.Rows.Count - 1, .Columns.Count).Copy vpRng
End If
End If
End With
With shAD.UsedRange
Set adRng = FilterWS(.Columns(REJECTED_COL), "Reject")
If Not adRng Is Nothing Then
If .Cells.CountLarge > 2 Then
Set vpRng = shVP.Cells(shVP.UsedRange.Rows.Count + 1, 1)
.Offset(1).Resize(.Rows.Count - 1, .Columns.Count).Copy vpRng
End If
End If
End With
With shAD.UsedRange
Set adRng = FilterWS(.Columns(REJECTED_COL), "Other")
If Not adRng Is Nothing Then
If .Cells.CountLarge > 2 Then
Set vpRng = shVP.Cells(shVP.UsedRange.Rows.Count + 1, 1)
.Offset(1).Resize(.Rows.Count - 1, .Columns.Count).Copy vpRng
End If
End If
End With
shAD.AutoFilterMode = False
'shVP.UsedRange.RemoveDuplicates Columns:=1, Header:=xlNo
'Sort shVP ----------------------------------------------------
Set vpRng = shVP.UsedRange.Columns(11)
With shVP.Sort
.SortFields.Clear
.SetRange shVP.UsedRange
.SortFields.Add Key:=vpRng, SortOn:=xlSortOnValues, Order:=xlAscending
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.Apply
End With
'Remove blanks from shVP --------------------------------------
With shVP.UsedRange
shVP.AutoFilterMode = False
If Len(shVP.Cells(1)) = 0 Then shVP.Cells(1) = "Header": flg = 1
Set vpRng = FilterWS(shVP.UsedRange.Columns(11), "=")
If Not vpRng Is Nothing Then
Set vpRng = shVP.UsedRange.Columns(2).SpecialCells(xlCellTypeVisible)
If .Cells.Count > 1 Then .SpecialCells(xlCellTypeVisible).EntireRow.Delete
End If
If flg = 1 Then shVP.Cells(1).EntireRow.Delete
shVP.AutoFilterMode = False
End With
Application.ScreenUpdating = True
'Copys qty recieved to amnt rejected if amt rejected is blank
With shVP
lr = .Cells(.Rows.Count, "A").End(xlUp).Row
For Each cel In .Range("G2:G" & lr) 'loop through each cell in Column
If (cel.Value) = "" Then 'check Command Name
Set fCell = cel.Offset(0, -3) 'set first cell to be copied in fCell
Set lCell = cel.Offset(0, 0)
lCell = fCell
End If
Next cel
End With
'Sorts data alphabetically by vendor
Application.ScreenUpdating = True
shVP.Activate
Cells.Select
Range("A:P").Activate 'old line a118
With Selection
.HorizontalAlignment = xlGeneral
.WrapText = False
.AddIndent = False
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
shVP.Range("A1").Select
' Array of header labels
headers() = Array("Warehouse", "Inspection Type", "ItemID", "QtyReceived", "UOM", "Sample::Sample", "DefectFound", _
"Disposition", "PurchOrder", "DISTRIBUTOR", "Manufacturer", "Remarks", "Date", "Cost", "RejectCat", "Date")
' Row to insert
shVP.Activate
Range("A1").EntireRow.Insert
With shVP
For i = LBound(headers()) To UBound(headers())
.Cells(1, 1 + i).Value = headers(i)
Next i
.Rows(1).Font.Bold = True
End With
End Sub
I have an Excel Workbook where the user imports a text file by the click of a button. My code works exactly as I need it to but it is extremely slow when filling in column H, Reading Date. Here is what my Excel Workbook looks like when the text file has been imported to the excel sheet:
Here is my code:
Sub Import_Textfiles()
Dim fName As String, LastRow As Integer
Worksheets("Data Importation Sheet").Activate
LastRow = Range("A" & Rows.Count).End(xlUp).Row + 1
' Finds the first blank row to import text file data to
fName = Application.GetOpenFilename("Text Files (*.txt), *.txt")
If fName = "False" Then Exit Sub
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & fName, _
Destination:=Range("A" & LastRow))
.Name = "2001-02-27 14-48-00"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = False
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 2
.TextFileParseType = xlFixedWidth
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1)
.TextFileFixedColumnWidths = Array(14, 14, 8, 16, 12, 14)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
ActiveWindow.SmallScroll Down:=0
Dim strShortName As String
'Adding Reading Date to Excel Sheet:
Dim rowCount As Integer, currentRow As Integer
Dim sourceCol As Integer, nextCol As Integer
Dim currentRowValue As String
Dim fileDate1 As String
Dim fileDate2 As String
sourceCol = 1 'columnA
nextCol = 8 'column H
rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row
strShortName = fName
fileDate1 = Mid(fName, InStrRev(fName, "\") + 1)
fileDate2 = Left(fileDate1, 10)
Cells(LastRow, 9) = ("Updating Location: " & strShortName)
For currentRow = 1 To rowCount
currentRowValue = Cells(currentRow, nextCol).Value
If currentRowValue = "" Then
Cells((currentRow), (nextCol)).Select
Cells((currentRow), (nextCol)) = fileDate2
End If
Next
End Sub
If anyone has any suggestions as to how I can speed up the importation of the reading date I would appreciate it greatly! Thanks in advance!
Few things that I noticed
As mentioned by Chris in comments, you can turn off screen updating and set calculation to manual and switch them back on and set calculation to automatic at the end of the code.
For Example
With Application
.ScreenUpdating = False
.Calculation = xlCalculationManual
End With
'
'~~> Rest of your code
'
With Application
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
End With
Avoid the use of .Select. it reduces the speed of the code. You do not need to select the cell to write to it.
Your For Loop can be written as.
For currentRow = 1 To RowCount
If Cells(currentRow, nextCol).Value = "" Then
Cells(currentRow, nextCol).Value = fileDate2
End If
Next
This it self will increase the speed of your code as you are not selecting the cell anymore before writing to it.
Ideally I would copy the range to an array and then do what you are doing with the array and then write it back to the cell but then that is me.
Remove unnecessary lines of code. ActiveWindow.SmallScroll Down:=0 is not needed.
Work with object(s) and fully qualify your object(s).
When working with Excel rows, use Long instead of Integer
Try this:
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
YOUR CODE HERE
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.EnableEvents = True
The best solution depends on a few things, that aren't clear to me from provided data. The following change will speed it up a lot (selecting cells takes a lot of time), but its not the optimum. If its still to slow, please provide ~ number of rows and ~% of rows (in column H), that are filled before you get to the following code. Then either searching for missing values or (probably in most cases) copying column H into an array and copying back after updating the values will do the trick.
Old code:
For currentRow = 1 To rowCount
currentRowValue = Cells(currentRow, nextCol).Value
If currentRowValue = "" Then
Cells((currentRow), (nextCol)).Select
Cells((currentRow), (nextCol)) = fileDate2
End If
Next
New code:
For currentRow = 1 To rowCount
if Cells(currentRow, nextCol).Value = "" then
Cells(currentRow,nextCol).Value = fileDate2
End If
Next
I have a vba script that brings in a .csv file and sorts it in excel. However there are some carriage returns on the end column and this is adding newlines in the import. I can fix this manually by going to the text file and replacing \n with "". But i would like this to be done automatically in the script before it is imported.
Here is my current script to import the text file:
For rep1 = 8 To 8
Dim i As Integer, j As Integer, pctCompl As Integer, myint As Integer
Dim lastrow As Long
Dim ws As Worksheet, ws1 As Worksheet, ws2 As Worksheet
Dim file_name As String
Dim file_name2 As String
Dim row_number As String
Dim output_sheet As String
Dim hour As String
Dim day As String
Dim month As String
Dim project As String
Set ws = Worksheets("Master")
Set ws1 = Worksheets("RAW_Data")
Set ws2 = Worksheets("BOM")
file_name = Sheets("Master").Range("F" & rep1).Value
file_name2 = Sheets("Master").Range("G" & rep1).Value
output_sheet = Sheets("Master").Range("L" & rep1).Value
row_number = Sheets("Master").Range("M" & rep1).Value
hour = Format(Sheets("Master").Range("I" & rep1).Value, "00")
day = Sheets("Master").Range("K" & rep1).Value
month = Sheets("Master").Range("J" & rep1).Value
project = Sheets("Master").Range("B2").Value
ws1.Activate
Columns("A:A").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Delete Shift:=xlToLeft
ws.Activate
aa = file_name2 & Format(Date, "yyyymmdd") & "_" & Format(Time, "Hh")
With Sheets(output_sheet).QueryTables.Add(Connection:="TEXT;" + file_name + "\" + month + "\" + day + "\" + file_name2 & Format(Date, "yyyymmdd") & "_" & hour & ".txt", Destination:=Sheets(output_sheet).Range("$A$" + row_number))
.Name = file_name & Format(Date, "yyyymmdd") & "_" & Format(Time, "Hh")
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlOverwriteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 850
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = "~"
.TextFileColumnDataTypes = Array(2, 2, 2, 2, 2, 9, 2, 9, 2, 2, 2, 2)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Next rep1
ws1.Activate
lastrow = Cells(ws1.Rows.Count, "A").End(xlUp).Row
Cells.Replace What:="true", Replacement:="TRUE", LookAt:=xlPart, _
searchorder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Cells.Replace What:="false", Replacement:="FALSE", LookAt:=xlPart, _
searchorder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
ws1.Columns("A:AZ").EntireColumn.AutoFit
ws2.UsedRange.ClearContents
ws2.Range("A1:G" & lastrow).Value = ActiveSheet.Range(Cells(1, 1), Cells(lastrow, 7)).Value
ws2.Range("N1:O" & lastrow).Value = ActiveSheet.Range(Cells(1, 8), Cells(lastrow, 9)).Value
ws2.Range("Y1:Y" & lastrow).Value = ActiveSheet.Range(Cells(1, 11), Cells(lastrow, 11)).Value
Your best bet would be to open the text file with something like an file system object, then replace() the character(s) you need, then write back to a temporary file and use that as an input. All of these steps are easily googleable, but if you get stuck, reply to this and I'll edit my post with more detail.