Data after closig and opening of excelI am having a tricky situation with my excel. I have written a VBA code which collects HEX data from many CSV file and converts it into decimal and stores it into decimal. This works perfectly when tested I had no problem, I had also saved it. But when I reopen the excel half the cells are back to Hex format and only half are in decimal. I don't know why this happens. When doing it for first time it works but on saving closing it and again opening it gives me this problem
Here is the vba code
OriginalData
Sub Sample()
Dim myfiles
Dim i As Integer
Dim J As Long
Dim l As Long
Dim LastRow As Long
myfiles = Application.GetOpenFilename(filefilter:="CSV Files (*.csv), *.csv", MultiSelect:=True)
If Not IsEmpty(myfiles) Then
For i = LBound(myfiles) To UBound(myfiles)
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & myfiles(i), Destination:=Range("A" & Rows.Count).End(xlUp).Offset(1, 0))
.Name = "Sample"
.FieldNames = False
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 3
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = True
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Next i
LR = Range("A" & Rows.Count).End(xlUp).Row
For J = 2 To LR
Cells(J, 4).Value = CLng("&H" & Mid(Cells(J, 4).Value, 4, Len(Cells(J, 4).Value)))
Cells(J, 5).Value = CLng("&H" & Mid(Cells(J, 5).Value, 8, Len(Cells(J, 5).Value)))
Cells(J, 6).Value = CLng("&H" & Mid(Cells(J, 6).Value, 8, Len(Cells(J, 6).Value)))
Cells(J, 7).Value = CLng("&H" & Mid(Cells(J, 7).Value, 8, Len(Cells(J, 7).Value)))
Cells(J, 8).Value = CLng("&H" & Mid(Cells(J, 8).Value, 4, Len(Cells(J, 8).Value)))
Cells(J, 9).Value = CLng("&H" & Mid(Cells(J, 9).Value, 8, Len(Cells(J, 9).Value)))
Next
LastRow = Range("C" & Rows.Count).End(xlUp).Row
For l = 2 To LastRow
'Cells(l, 14).Value = Left(Cells(l, 3).Value, 3)
'Cells(l, 13).Value = Right(Range(l, 3).Value, 4)
'(l, 12).Value = Val(Left(Right(Cells(l, 3).Value, 7), 2))
Cells(l, 10).Value = Left(Cells(l, 3).Value, 3) + Val(Left(Right(Cells(l, 3).Value, 7), 2)) / 60 + Right(Cells(l, 3).Value, 4) / 3600
Next
Else
MsgBox "No File Selected"
End If
End Sub
I parse more than one CSV files at the same time so when on reopening only the parse of the first file remains in decimal format others change to original hex format
Related
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
this is the code i am using and its working fine but for one row only .I need to make it generic to apply it on all rows of the text file.I have total 150 rows in text file.How can i loop it while making next line as end of record.
Code:
Public Sub Convert_TxtFile()
Dim myStr As String
myStr = FileText("C:\Users\BS255028\Desktop\Book2.txt")
Cells(1, 1) = Mid(myStr, 1, 4)
Cells(1, 2) = Mid(myStr, 5, 3)
Cells(1, 3) = Mid(myStr, 8, 8)
Cells(1, 4) = Mid(myStr, 16, 2)
End Sub
Function FileText(ByVal filename As String) As String
Dim nFileNum As Integer
If Len(Dir$(filename)) = 0 Then
Err.Raise 53
End If
nFileNum = FreeFile
Open filename$ For Binary As #nFileNum
FileText = Space$(LOF(nFileNum))
Get #nFileNum, , FileText
Close #nFileNum
End Function
You could simply record a macro of you importing the text file. Using fixed widths will allow you to split the text into columns based on the desired widths.
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Users\BS255028\Desktop\Book2.txt", _
Destination:=Range("$A$1"))
.Name = "adam_styborskis_pauper_cube"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlFixedWidth
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1)
.TextFileFixedColumnWidths = Array(4, 3, 8, 2)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
Untested:
Public Sub Convert_TxtFile()
Dim myStr As String, s, arr, i As Long
myStr = FileText("C:\Users\BS255028\Desktop\Book2.txt")
arr = Split(myStr, vbCrLf)
i = 1
for each s in arr
Cells(i, 1).Resize(1, 4) = Array(Mid(myStr, 1, 4), Mid(myStr, 5, 3), _
Mid(myStr, 8, 8), Mid(myStr, 16, 2))
i = i + 1
next
End Sub
Not sure how FileText works, but if it puts the text in to 150 rows in Excel, you can just add a loop:
Public Sub Convert_TxtFile()
Dim myStr As String
Dim i as Long
myStr = FileText("C:\Users\BS255028\Desktop\Book2.txt")
For i = 1 to 150
Cells(i, 1) = Mid(myStr, 1, 4)
Cells(i, 2) = Mid(myStr, 5, 3)
Cells(i, 3) = Mid(myStr, 8, 8)
Cells(i, 4) = Mid(myStr, 16, 2)
Next i
End Sub
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.
Im trying to get a list of all folders in a directory. and have a button that enables an update, on the list, without re-creating it every time. So only listing new folder that are not already in the excel sheet.
This is the code that I have working. But I would like it to be able to search the sheet if the folder is already there, if it is then skip it, if not the add it. Once the update it completed the filter by name in column C
Sub folder_names_including_subfolder()
Application.ScreenUpdating = False
Dim fldpath
Dim fso As Object, j As Long, folder1 As Object
If ActiveSheet.Name = "test" Then
fldpath = "Z:\\"
ElseIf ActiveSheet.Name = "test1" Then
fldpath = "Y:\\"
End If
Cells(3, 1).Value = fldpath
Cells(4, 1).Value = "Path"
Cells(4, 2).Value = "Dir"
Cells(4, 3).Value = "Name"
Cells(4, 4).Value = "Folder Size"
Cells(4, 5).Value = "Date Created"
Cells(4, 6).Value = "Date Last Modified"
Cells(4, 7).Value = "Codec"
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder1 = fso.GetFolder(fldpath)
get_sub_folder folder1
Set fso = Nothing
Range("A3").Font.Size = 9
ActiveWindow.DisplayGridlines = False
Range("A3:G" & Range("A4").End(xlDown).Row).Font.Size = 9
Range("A4:G4").Interior.Color = vbCyan
Application.ScreenUpdating = True
End Sub
Sub get_sub_folder(ByRef prntfld As Object)
Dim SubFolder As Object, subfld As Object, j As Long
For Each SubFolder In prntfld.SubFolders
j = Range("A3").End(xlDown).Row + 1
Cells(j, 1).Value = SubFolder.Path
Cells(j, 2).Value = Left(SubFolder.Path, InStrRev(SubFolder.Path, "\"))
Cells(j, 3).Value = SubFolder.Name
Cells(j, 4).Value = Application.WorksheetFunction.RoundDown((((SubFolder.Size / 1024) / 1024) / 1024), 2) & " " & "GB"
Cells(j, 5).Value = SubFolder.DateCreated
Cells(j, 6).Value = SubFolder.DateLastModified
With Cells(j, 7).Validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=Sheet3!$A$1:$A$5"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
Next SubFolder
For Each subfld In prntfld.SubFolders
get_sub_folder subfld
Next subfld
Columns("C:F").AutoFit
Columns("G").ColumnWidth = 10
End Sub
Just test before storing the material:
For Each SubFolder In prntfld.SubFolders
checkit = SubFolder.Name
If Application.WorksheetFunction.CountIf(Range("C:C"), checkit) = 0 Then
j = Range("A3").End(xlDown).Row + 1
Cells(j, 1).Value = SubFolder.Path
Cells(j, 2).Value = Left(SubFolder.Path, InStrRev(SubFolder.Path, "\"))
Cells(j, 3).Value = SubFolder.Name
Cells(j, 4).Value = Application.WorksheetFunction.RoundDown((((SubFolder.Size / 1024) / 1024) / 1024), 2) & " " & "GB"
Cells(j, 5).Value = SubFolder.DateCreated
Cells(j, 6).Value = SubFolder.DateLastModified
With Cells(j, 7).Validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=Sheet3!$A$1:$A$5"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
End If
Next SubFolder
I have created an excel that using a vba code access yahoo web site to fetch stocks data.
The excel works fine most of the time but sometimes (and I can't find a rule/ motivation) it does not get the data from yahoo.
The strange thing is that if I do it step by step using the debugger it works but if I start the macro it does not work and am not able to fetch the data.
Do you have any idea?
Thanks,
Giancarlo
Below the subs I use t retrieve the data ...
Sub StrongestSmallCaps()
Dim frequency As String
Dim numRows As Integer
Dim LastRow As Integer
Dim stockTicker As String
Dim IndR As Integer
Dim Simbolo As String
Dim rsi As String
Dim ShortInter As Boolean
Dim NonIncr As Boolean
Worksheets("GreenLine").Select
LastRow = ActiveSheet.Cells(Rows.Count, "h").End(xlUp).Row
frequency = "d"
'Cancella contenuti celle stocastici
Range("j2:k70").Clear
Range("j2:k70").Select
Selection.Style = "Stocastic"
Range("i2:i70").Clear
Range("i2:i70").Select
Selection.Style = "Tick"
Application.Wait Now + TimeValue("00:00:03")
IndR = 2
'Loop through all tickers
For Ticker = 2 To LastRow
'Application.Wait Now + TimeValue("00:00:03")
stockTicker = Worksheets("GreenLine").Range("$h$" & Ticker)
If stockTicker = "" Then
GoTo NextIteration
End If
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = stockTicker
Cells(1, 1) = "Stock Quotes for " & stockTicker
Call DownloadStockQuotes(stockTicker, Worksheets("GreenLine").Range("$b$500"), Worksheets("GreenLine").Range("$b$600"), "$a$2", frequency)
'Application.Wait Now + TimeValue("00:00:03")
Columns("a:a").TextToColumns Destination:=Range("a1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=True, Space:=False, other:=False, FieldInfo:=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), Array(7, 1))
Sheets(stockTicker).Columns("A:G").ColumnWidth = 10
LastRow = Sheets(stockTicker).UsedRange.Row - 2 + Sheets(stockTicker).UsedRange.Rows.Count
If LastRow < 3 Then
Application.DisplayAlerts = False
Sheets(stockTicker).delete
GoTo NextIteration
Application.DisplayAlerts = True
End If
Rows("1:1").Select
Selection.delete Shift:=xlUp
Columns("B:B").Select
Selection.delete Shift:=xlToLeft
Columns("E:E").Select
Selection.delete Shift:=xlToLeft
Columns("E:E").Select
Selection.delete Shift:=xlToLeft
Rows("2:2").Select
Selection.INSERT Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
'CALCOLA STOCHASTIC
Worksheets("GreenLine").Select
Range("Cb100:Cm122").Select
Selection.Copy
Worksheets("GreenLine").Select
Sheets(stockTicker).Select
Range("e1").Select
ActiveSheet.Paste
If Cells(3, 8) < 20 Then
Worksheets("GreenLine").Select
Cells(IndR, 9) = stockTicker
Cells(IndR, 10) = "BUY"
Cells(IndR, 10).Select
Selection.Style = "Oversold"
Application.DisplayAlerts = False
Sheets(stockTicker).delete
Application.DisplayAlerts = True
'CALCOLA RSI
'Sheets(stockTicker).Select
'If Cells(3, 16) < 20 Then
' rsi = Cells(3, 16)
' Worksheets("GreenLine").Select
'
' Cells(IndR, 9) = stockTicker
' Cells(IndR, 11) = "OVS"
' Cells(IndR, 11).Select
' Selection.Style = "Oversold"
' Selection.Style = "Comma"
' IndR = IndR + 1
' Application.DisplayAlerts = False
' Sheets(stockTicker).delete
' Application.DisplayAlerts = True
'Else
' IndR = IndR + 1
' Application.DisplayAlerts = False
' Sheets(stockTicker).delete
' Application.DisplayAlerts = True
'End If
Else
Application.DisplayAlerts = False
Sheets(stockTicker).delete
Application.DisplayAlerts = True
'Sheets(stockTicker).Select
'If Cells(3, 16) < 20 Then
' rsi = Cells(3, 16)
' Worksheets("GreenLine").Select
'
' Cells(IndR, 9) = stockTicker
' Cells(IndR, 11) = "OVS"
' Cells(IndR, 11).Select
' Selection.Style = "Oversold"
' Selection.Style = "Comma"
'
' IndR = IndR + 1
' Application.DisplayAlerts = False
' Sheets(stockTicker).delete
' Application.DisplayAlerts = True
'Else
' Application.DisplayAlerts = False
' Sheets(stockTicker).delete
' Application.DisplayAlerts = True
'End If
End If
NextIteration:
Next Ticker
ErrorHandler:
Worksheets("GreenLine").Select
Application.ScreenUpdating = True
Range("h2:h70").Clear
Range("h2:h70").Select
Selection.Style = "Normal"
E
nd Sub
Sub DownloadStockQuotes(ByVal stockTicker As String, ByVal startDate As Date, ByVal endDate As Date, ByVal DestinationCell As String, ByVal freq As String)
Dim qurl As String
Dim StartMonth, StartDay, StartYear, EndMonth, EndDay, EndYear As String
StartMonth = Format(Month(Date) - 8, "00")
StartDay = Format(Day(Date), "00")
StartYear = Format(Year(Date), "00")
EndMonth = Format(Month(Date) - 1, "00")
EndDay = Format(Day(Date), "00")
EndYear = Format(Year(Date), "00")
Application.Wait Now + TimeValue("00:00:03")
qurl = "URL;http://table.finance.yahoo.com/table.csv?s=" + stockTicker + "&a=" + StartMonth + "&b=" + StartDay + "&c=" + StartYear + "&d=" + EndMonth + "&e=" + EndDay + "&f=" + EndYear + "&g=" + freq + "&ignore=.csv"
Application.Wait Now + TimeValue("00:00:03")
On Error GoTo ErrorHandler:
With ActiveSheet.QueryTables.Add(Connection:=qurl, Destination:=Range(DestinationCell))
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.WebSelectionType = xlSpecifiedTables
.WebFormatting = xlWebFormattingNone
.WebTables = "20"
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.WebSingleBlockTextImport = False
.WebDisableDateRecognition = False
.WebDisableRedirections = False
.Refresh BackgroundQuery:=False
End With
ErrorHandler:
End Sub
What I do is I issue this command first
On Error Resume Next ' this should get past 1004 errors but No Data will show in my error column
Then after I fetch the data, I check to see if there is really any data there and if not, I run the query again.
For some unknown reason it randomly fails and almost always works the second time.
But I hope you already solved your problem since it was posted so long ago.