I am running the following working Macro on word visual basic. Each time I run it, the macro successfully generates the report how I want it to; but then I look in the task manager and I see that an instance of excel is still running. I run the debugger over the code, the debugger goes through the final line:
oExcel.quit
and yet it still doesn't terminate the application!
Sub WriteExtension()
'
' WriteExtension Macro
'
'
copyFile
Dim nWord As New Document
word.Application.ScreenUpdating = False
Set nWord = Documents.Open("c:\output\report\here\report", Visible:=False)
'initialize excel variables
Dim oExcel As Excel.Application
Dim oWorkbook As workbook
Dim oWorksheet As worksheet
'initialize excel object
Set oExcel = New Excel.Application
oExcel.ScreenUpdating = False
Set oWorkbook = oExcel.Workbooks.Open("c:\spreadsheet\here\spreadsheet.xlsx")
Set oWorksheet = oWorkbook.Worksheets(Sheets("Extensions").Index)
'setup loop variables
Dim tempString As String
Dim delim As String
Dim i As Long
Dim bkMark As Bookmark
Dim questions(13) As String
questions(0) = 13
questions(1) = 15
questions(2) = 17
questions(3) = 19
questions(4) = 29
questions(5) = 31
questions(6) = 33
questions(7) = 36
questions(8) = 38
questions(9) = 40
questions(10) = 42
questions(11) = 46
questions(12) = 48
delim = "#"
tempString = delim & Join(questions, delim)
Dim bmrange As Range
For i = 1 To 78
If (InStr(1, tempString, delim & i & delim, vbTextCompare)) Then
Set bmrange = nWord.Bookmarks("BM" & (i)).Range
If (Cells(4, i + 6) = 1) Then
nWord.ContentControls.Add(wdContentControlCheckBox, bmrange).Checked = True
Else
nWord.ContentControls.Add(wdContentControlCheckBox, bmrange).Checked = False
End If
ElseIf (InStr(1, tempString, delim & (i - 1) & delim, vbTextCompare)) Then
Set bmrange = nWord.Bookmarks("BM" & (i)).Range
If (Cells(4, i + 6) = 1) Then
nWord.ContentControls.Add(wdContentControlCheckBox, bmrange).Checked = True
Else
nWord.ContentControls.Add(wdContentControlCheckBox, bmrange).Checked = False
End If
Else
nWord.Bookmarks.Item("BM" & i).Range.InsertAfter (Cells(4, i + 6))
End If
Next i
Dim filePath As String
Dim fileName As String
Dim newName As String
' save the file as a PDF and close the PDF
filePath = "c:\output\report\here\report"
fileName = Cells(4, 13) & Cells(4, 12) & Cells(4, 79) & ".pdf"
newName = filePath & fileName
nWord.SaveAs2 fileName:=newName, FileFormat:=wdFormatPDF
' Close things
nWord.Close False
oWorkbook.Close False
oExcel.Quit
End Sub
I suspect that your issue is related to your unqualified Sheets and Cells references.
Set oWorksheet = oWorkbook.Worksheets(Sheets("Extensions").Index) should probably just be Set oWorksheet = oWorkbook.Worksheets("Extensions") (no need to get the index of a sheet by using its name just to get a reference to the sheet, when you can just index it by its name) and Cells(4, i + 6) should probably be oWorksheet.Cells(4, i + 6).
I could replicate your issue before I made those changes (although sometimes the code would just crash), but once I fixed them Excel correctly closed at the End Sub. (It didn't disappear after the oExcel.Quit because oExcel wasn't Nothing yet.)
Sub WriteExtension()
'
' WriteExtension Macro
'
'
copyFile
Dim nWord As New Document
word.Application.ScreenUpdating = False
Set nWord = Documents.Open("c:\output\report\here\report", Visible:=False)
'initialize excel variables
Dim oExcel As Excel.Application
Dim oWorkbook As workbook
Dim oWorksheet As worksheet
'initialize excel object
Set oExcel = New Excel.Application
oExcel.ScreenUpdating = False
Set oWorkbook = oExcel.Workbooks.Open("c:\spreadsheet\here\spreadsheet.xlsx")
Set oWorksheet = oWorkbook.Worksheets("Extensions")
'setup loop variables
Dim tempString As String
Dim delim As String
Dim i As Long
Dim bkMark As Bookmark
Dim questions(13) As String
questions(0) = 13
questions(1) = 15
questions(2) = 17
questions(3) = 19
questions(4) = 29
questions(5) = 31
questions(6) = 33
questions(7) = 36
questions(8) = 38
questions(9) = 40
questions(10) = 42
questions(11) = 46
questions(12) = 48
delim = "#"
tempString = delim & Join(questions, delim)
Dim bmrange As Range
For i = 1 To 78
If (InStr(1, tempString, delim & i & delim, vbTextCompare)) Then
Set bmrange = nWord.Bookmarks("BM" & (i)).Range
If oWorksheet.Cells(4, i + 6) = 1 Then
nWord.ContentControls.Add(wdContentControlCheckBox, bmrange).Checked = True
Else
nWord.ContentControls.Add(wdContentControlCheckBox, bmrange).Checked = False
End If
ElseIf InStr(1, tempString, delim & (i - 1) & delim, vbTextCompare) Then
Set bmrange = nWord.Bookmarks("BM" & (i)).Range
If oWorksheet.Cells(4, i + 6) = 1 Then
nWord.ContentControls.Add(wdContentControlCheckBox, bmrange).Checked = True
Else
nWord.ContentControls.Add(wdContentControlCheckBox, bmrange).Checked = False
End If
Else
nWord.Bookmarks.Item("BM" & i).Range.InsertAfter (oWorksheet.Cells(4, i + 6))
End If
Next i
Dim filePath As String
Dim fileName As String
Dim newName As String
' save the file as a PDF and close the PDF
filePath = "c:\output\report\here\report"
fileName = oWorksheet.Cells(4, 13) & oWorksheet.Cells(4, 12) & oWorksheet.Cells(4, 79) & ".pdf"
newName = filePath & fileName
nWord.SaveAs2 fileName:=newName, FileFormat:=wdFormatPDF
' Close things
nWord.Close False
oWorkbook.Close False
oExcel.Quit
'Optional: Set Excel objects to Nothing so that Excel closes now instead of at End Sub
Set oWorkbook = Nothing
Set oExcel = Nothing
End Sub
Related
When I try to generate a word document, it gets stopped at the 80% progress bar and it shows the following error.
When I try to debug it, I see this
I'm getting error in now For i = 1 To .InlineShapes.Count
My code
Sub FillABookmark(strBM As String, strText As String)
Dim j As Long
With ActiveDocument
.Bookmarks(strBM).Range _
.InlineShapes _
.AddPicture FileName:=strText
j = ActiveDocument.InlineShapes.Count
.InlineShapes(j).Select
.Bookmarks.Add strBM, Range:=Selection.Range
End With
End Sub
Sub AddImage(strFile As String, addOrAfter As Boolean)
Dim oImage As Object
'Dim oDialog As Dialog
' Dim oRng As Object
' Set oDialog = Dialogs(wdDialogInsertPicture)
' With oDialog
' .Display
' If .Name <> "" Then
' strFile = .Name
' End If
'End With
'Selection.Move 6, -1 'moverse al principio del documento
'Selection.Find.Execute FindText:="[aud_sig_1]"
'If Selection.Find.Found = True Then
If (addOrAfter) Then
Set oImage = Selection.InlineShapes.AddPicture(strFile, False, True)
'With oRng
' .RelativeHorizontalPosition = _
' wdRelativeHorizontalPositionPage
' .RelativeVerticalPosition = _
' wdRelativeVerticalPositionPage
'.Left = CentimetersToPoints(0)
'.Top = CentimetersToPoints(4.5)
'End With
Else
Selection.TypeParagraph
Selection.TypeParagraph
Selection.TypeParagraph
Selection.TypeParagraph
Selection.TypeParagraph
Set oImage = Selection.InlineShapes.AddPicture(strFile, False, True)
End If
With oImage
.LockAspectRatio = msoFalse
.Height = CentimetersToPoints(1.5)
.Width = CentimetersToPoints(2.1)
Set oRng = .ConvertToShape
End With
Set oDialog = Nothing
Set oImage = Nothing
Set oRng = Nothing
End Sub
Sub PicWithCaption(xPath, Optional ByVal imgType As String = "All")
Dim xFileDialog As FileDialog
Dim xFile As Variant
Dim doc As Document
'******Test
'Set doc = Application.ActiveDocument
'xPath = "C:\phototest\"
'doc.Bookmarks.Exists ("photos")
'doc.Bookmarks("photos").Select 'select the bookmark
'*****End test
Dim x, w, c
Dim oTbl As Word.Table, i As Long, j As Long, k As Long, StrTxt As String
Set oTbl = Selection.Tables.Add(Selection.Range, 2, 3)
With oTbl
.AutoFitBehavior (wdAutoFitFixed)
.Columns.Width = CentimetersToPoints(9)
'Format the rows
Call FormatRows(oTbl, 1)
End With
If xPath <> "" Then
xFile = Dir(xPath & "\*.*")
i = 1
CaptionLabels.Add Name:="Picture"
Do While xFile <> ""
If (UCase(Right(xFile, 3)) = "PNG" Or _
UCase(Right(xFile, 3)) = "TIF" Or _
UCase(Right(xFile, 3)) = "JPG" Or _
UCase(Right(xFile, 3)) = "GIF" Or _
UCase(Right(xFile, 3)) = "BMP") And (imgType = "All" Or UCase(Left(xFile, 1) <> imgType)) Then
j = Int((i + 2) / 3) * 2 - 1
k = (i - 1) Mod 3 + 1
'Add extra rows as needed
If j > oTbl.Rows.Count Then
oTbl.Rows.Add
oTbl.Rows.Add
Call FormatRows(oTbl, j)
End If
'Insert the Picture
'Dim shape As InlineShape
' ActiveDocument.InlineShapes.AddPicture _
' FileName:=xPath & "\" & xFile, LinkToFile:=False, _
' SaveWithDocument:=True, Range:=oTbl.Rows(j).Cells(k).Range
Set shape = ActiveDocument.InlineShapes.AddPicture(xPath & "\" & xFile, False, True, oTbl.Rows(j).Cells(k).Range)
oTbl.Rows(j).Cells(k).Range.ParagraphFormat.Alignment = wdAlignParagraphCenter
' With shape
' .LockAspectRatio = msoTrue
' If .Width > .Height Then
' .Height = InchesToPoints(1.75)
' Else
' .Width = InchesToPoints(1.75)
' End If
' End With
'shape.ScaleWidth = 50
'Get the Image name for the Caption
'StrTxt = Split(xPath & "\" & xFile, "\")(UBound(Split(.SelectedItems(i), "\")))
StrTxt = xFile
StrTxt = ": " & Split(StrTxt, ".")(0)
'Insert the Caption on the row below the picture
With oTbl.Rows(j + 1).Cells(k).Range
.InsertBefore vbCr
.Characters.First.InsertParagraph
.InsertBefore StrTxt
.ParagraphFormat.Alignment = wdAlignParagraphCenter
.Font.Bold = True
.Characters.First = vbNullString
.Characters.Last.Previous = vbNullString
End With
End If
i = i + 1
xFile = Dir()
Loop
End If
'End If
End Sub
Sub FormatRows(oTbl As Table, x As Long)
With oTbl
With .Rows(x)
.Height = CentimetersToPoints(6)
.HeightRule = wdRowHeightExactly
.Range.Style = "Normal"
.Alignment = wdAlignRowCenter
End With
With .Rows(x + 1)
.Height = CentimetersToPoints(1.2)
.HeightRule = wdRowHeightExactly
.Range.Style = "Caption"
.Alignment = wdAlignRowCenter
End With
End With
End Sub
Sub rezie()
Dim i As Long
With ThisDocument
For i = 1 To .InlineShapes.Count
Next i
End With
End Sub
Use the style enums to be on the safe side when on a non-english system:
.Range.Style = Word.wdStyleCaption (in case you are using early binding - what you are using)
In case of late binding: .Range.style = -35
I have a process that I run on sets of workbooks. I'm trying to modify the filetype when I close the file. I'm trying to tack it onto the end of the process before closing each workbook. Right now, the opened file is in .xlsb. I'm trying to save it in basically any other format (.xsls, etc.)
Whenever I run the Macro the "SaveAs" command errors out. I've tried everything I can think of to have it just save the file with the same name, different filetype, but no luck.
What am I doing wrong?
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Path = ThisWorkbook.Sheets(1).Range("H6")
If Right(Path, 1) <> "\" Then
Path = Path & "\"
End If
wsheet = ThisWorkbook.Sheets(1).Range("F10")
ThisWorkbook.Sheets(3).Range("A2:B20000").ClearContents
OutLn = 2
Line = 1
Do While ThisWorkbook.Sheets(2).Cells(Line, 1) <> ""
OpnFil = ThisWorkbook.Sheets(2).Cells(Line, 1)
Workbooks.Open fileName:=Path & OpnFil, UpdateLinks:=False
ScanLn = 12
Do While ThisWorkbook.Sheets(1).Cells(ScanLn, 5) <> ""
ThisWorkbook.Sheets(3).Cells(OutLn, 1) = OpnFil
Addr = ThisWorkbook.Sheets(1).Cells(ScanLn, 5)
ThisWorkbook.Sheets(3).Cells(OutLn, 2) = Workbooks(OpnFil).Sheets(wsheet).Range(Addr)
OutLn = OutLn + 1
ScanLn = ScanLn + 1
Loop
Workbooks(OpnFil).SaveAs fileName:=Workbooks(OpnFil).GetBaseName, FileFormat:=51
Workbooks(OpnFil).Close
Line = Line + 1
Loop
End Sub```
Backup Workbooks
Use variables to avoid (long) unreadable lines (parameters).
Option Explicit
Sub BackupWorkbooks()
Dim swb As Workbook: Set swb = ThisWorkbook
Dim dFolderPath As String: dFolderPath = swb.Sheets(1).Range("H6").Value
If Right(dFolderPath, 1) <> "\" Then
dFolderPath = dFolderPath & "\"
End If
Dim dwsName As String: dwsName = swb.Sheets(1).Range("F10").Value
Application.ScreenUpdating = False
swb.Sheets(3).Range("A2:B" & swb.Sheets(3).Rows.Count).ClearContents
Dim OutLn As Long: OutLn = 2
Dim Line As Long: Line = 1
Dim dwb As Workbook
Dim dOldName As String
Dim dOldPath As String
Dim dNewPath As String
Dim dAddr As String
Dim ScanLn As Long
Do While swb.Sheets(2).Cells(Line, 1) <> ""
dOldName = swb.Sheets(2).Cells(Line, 1)
dOldPath = dFolderPath & dOldName
Set dwb = Workbooks.Open(Filename:=dOldPath, UpdateLinks:=False)
ScanLn = 12
Do While swb.Sheets(1).Cells(ScanLn, 5).Value <> ""
swb.Sheets(3).Cells(OutLn, 1).Value = dOldName
dAddr = swb.Sheets(1).Cells(ScanLn, 5).Value
swb.Sheets(3).Cells(OutLn, 2).Value _
= dwb.Worksheets(dwsName).Range(dAddr).Value
OutLn = OutLn + 1
ScanLn = ScanLn + 1
Loop
dNewPath = Left(dOldPath, InStrRev(dOldPath, ".") - 1) & ".xlsx"
' Or if you insist:
'dNewPath = dFolderPath & CreateObject("Scripting.FileSystemObject") _
.GetBaseName(dOldName) & ".xlsx"
Application.DisplayAlerts = False
dwb.SaveAs Filename:=dNewPath, FileFormat:=xlOpenXMLWorkbook ' 51
Application.DisplayAlerts = True
dwb.Close
Line = Line + 1
Loop
Application.ScreenUpdating = True
MsgBox "Backups created.", vbInformation, "Backup Workbooks"
End Sub
I just started working with VBA.
I have a VBA code that counts the number of the occurence of words inside the excel file. It works fine.
I want to run this VBA macro on all files I have inside a specific folder.
Could you help me out?
My code below:
I am getting values right only for the file from which I ran the macro. For the rest of the files, the reults obtained are wrong
Sub LoopThroughFiles()
Dim xFd As FileDialog
Dim xFdItem As Variant
Dim xFileName As String
Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
If xFd.Show = -1 Then
xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
xFileName = Dir(xFdItem & "*.xls*")
Do While xFileName <> ""
With Workbooks.Open(xFdItem & xFileName)
Dim wordList As New Collection
Dim keyList As New Collection
Dim c
Worksheets("Sheet1").Activate
Dim RangeToCheck As Range
Set RangeToCheck = Range("A1:A1000")
For Each c In RangeToCheck
Dim words As Variant
words = Split(c, " ")
For Each w In words
Dim temp
temp = -1
On Error Resume Next
temp = wordList(w)
On Error GoTo 0
If temp = -1 Then
wordList.Add 1, Key:=w
keyList.Add w, Key:=w
Else
wordList.Remove (w)
keyList.Remove (w)
wordList.Add temp + 1, w
keyList.Add w, Key:=w
End If
Next w
Next c
Dim x
Dim k
k = 1
For x = 1 To wordList.Count
With Sheets("Sheet1")
.Cells(k, "E").Value = keyList(x)
.Cells(k, "F").Value = wordList(x)
k = k + 1
End If
End With
Next x
End With
xFileName = Dir
Loop
End If
End Sub
Try this
Public Sub LoopThroughFiles()
Dim xFd As FileDialog
Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
xFd.AllowMultiSelect = False
If xFd.Show <> -1 Then
MsgBox "No Folder selected": Exit Sub
End If
Dim Folder As String: Folder = xFd.SelectedItems(1) & "\"
Dim Files
Files = Dir(Folder & "*.xls*")
Dim Xls As String
On Error Resume Next
Dim CrWB As Workbook, CrSheet As Worksheet
Dim ClnW As New Collection, ClnC As New Collection
Dim Cols As Integer: Cols = 1
Do While Files <> ""
Xls = Replace(Folder & Files, "\\", "\")
Set CrWB = Application.Workbooks.Open(Xls, , True)
Set CrSheet = CrWB.Sheets("Sheet1")
If Err.Number > 0 Then
MsgBox "Can't open File " & Xls & vbCrLf & Err.Description
Err.Clear
GoTo 1
End If
Dim c As Range
Set ClnW = New Collection: Set ClnC = New Collection
For Each c In CrSheet.Range("A1:A1000")
If c.Value <> "" Then
Words = Split(CStr(c.Value), " ", , vbTextCompare)
For Each s In Words
Err.Clear
tmp = ClnW(s)
If Err.Number > 0 Then
ClnW.Add Item:=s, Key:=s
ClnC.Add Item:=1, Key:=s
Else
x = ClnC(s) + 1
ClnC.Remove s
ClnC.Add Item:=x, Key:=s
End If
Next
End If
Next
Set CrSheet = ThisWorkbook.Sheets("Sheet1")
With CrSheet
.Cells(1, Cols).Value = Files
.Cells(2, Cols).Value = "Word"
.Cells(2, Cols + 1).Value = "Occurance"
.Range(.Cells(1, Cols), .Cells(1, Cols + 1)).Merge
Dim I As Integer: I = 3
For Each s In ClnW
.Cells(I, Cols).Value = s
.Cells(I, Cols + 1).Value = ClnC(s)
I = I + 1
Next
End With
Cols = Cols + 2
1
CrWB.Close False
Files = Dir()
Err.Clear
Loop
End Sub
Just a short question, how to generate a barcode in excel worksheet? The barcode-text has been specified in a cell.
(Not intent to mass generate barcodes which otherwise can be done in MS Word.)
Select the range where barcode-text is written:
Then run the following script:
Sub INSERT_BARCODE()
Const BarcodeWidth As Integer = 156
Dim ws As Worksheet, WdApp
Set ws = ActiveSheet
Set WdApp = CreateObject("Word.Application")
With WdApp.Documents.Add
.PageSetup.RightMargin = .PageSetup.PageWidth - .PageSetup.LeftMargin - BarcodeWidth
.Fields.Add(Range:=.Range, Type:=-1, Text:="DISPLAYBARCODE " & CStr(Selection.Value) & " CODE39 \d \t", PreserveFormatting:=False).Copy
End With
ws.PasteSpecial Format:="Picture (Enhanced Metafile)", Link:=False, DisplayAsIcon:=False
WdApp.Quit SaveChanges:=False
Set WdApp = Nothing
End Sub
Note:
Change the encoding rule as you like. This example uses CODE39 rule. Refer https://msdn.microsoft.com/en-us/library/hh745901(v=office.12).aspx for more details.
Adjust the BarcodeWidth interger to best fit the barcode.
BR~
This is massively over-specced for what you need, but you can pull the bits out of it as required.
Sub Call_Barcode_Service()
Dim strResource As String
Dim strSize As String
Dim iHgt As Integer
Dim iWth As Integer
Dim iGap As Integer
Dim PictureGrab As String
Dim lngLastRow As Long
strSize = UCase(InputBox("How Big?", "Small, Medium or Large?", "L"))
Select Case strSize
Case Is = "S"
iWth = 150
iHgt = 45
iGap = 3
Case Is = "M"
iWth = 150
iHgt = 60
iGap = 4
Case Is = "L"
iWth = 240
iHgt = 75
iGap = 5
Case Else
iWth = 250
iHgt = 75
iGap = 5
End Select
Set sel = Selection.SpecialCells(xlTextValues)
Set news = Worksheets.Add()
news.Name = "Barcodes"
Set op = news.Range("A1")
For Each acc In sel
strResource = acc.Value
PictureGrab = "http://www.barcodesinc.com/generator/image.php?code=" & strResource & "&style=197&type=C128B&width=" & iWth & "&height=" & iHgt & "&xres=1&font=1"
Set sh = ActiveSheet.Shapes.AddShape(msoShapeRectangle, op.Left, op.Top, iWth, iHgt)
With sh
.Name = strResource
.Line.Visible = False
.Fill.UserPicture PictureGrab
End With
Set op = op.Offset(iGap + 1, 0).Range("A1")
Next
Range("G1").Select
End Sub
I use word with Macro :
Sub Macro1()
'
' Macro1 Macro
' Test Barcode
'
Dim codei As String
Dim codej As String
For I = 1 To 1 '0
For J = 1 To 2 '0
codei = CStr(I)
While Len(codei) < 2
codei = "0" & codei
Wend
codej = CStr(J)
While Len(codej) < 4
codej = "0" & codej
Wend
codei = codei & codej
Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, _
PreserveFormatting:=False
Selection.TypeText Text:="DisplayBarcode " & codei & " Code128 \t"
Selection.TypeParagraph
Selection.Fields.Update
Next J
Next I
End Sub
I've written a macro that downloads zip files containing CSVs from a website. The downloading and unzipping is going perfectly, however when I try to loop through the CSVs searching for the occurrence of a specific string, the macro simply quits after opening about a thousand. There is no error message, it simply stops working, leaving the last CSV it was working on open.
Here is my code:
Sub OpenSearch()
Dim ROW, j As Integer
Workbooks.Open Filename:=FileNameFolder & FileListCSV(i)
For j = 1 To 7
ROW = 3
Do Until IsEmpty(Cells(ROW, 6))
If Cells(ROW, 6) = WantedID(j, 1) Then
MsgBox "WE HAVE A MATCH!"
End If
ROW = ROW + 1
Loop
Next j
Workbooks(FileListCSV(i)).Close False
Kill FileNameFolder & FileListCSV(i)
End Sub
I did not include the main module that calls the this sub and downloads and unzips the files, because on its own, that works perfectly. It only stops working when the sub I copied here is being called.
The Filename comes from a public variable defined in the main module, WantedID contains the strings I need to find in the CSVs.
I've tried to put Application.Wait in the first line, but it did not solve the problem. Also how far the macro gets is completely random. It never stops after the same number of CSVs opened and closed.
UPDATE: Here is the code (parent sub) for the downloading and unzipping. I did not come up with this on my own, but copied it from an online source I cannot recall:
Public FileListCSV(1 To 288) As String
Public i As Integer
Public FileNameFolder As Variant
Public WantedID As Variant
Sub DownloadandUnpackFile()
Dim myURL As String
Dim YearNUM As Integer
Dim MonthNUM As Integer
Dim StarMonth, EndMonth As Integer
Dim DayNUM As Integer
Dim YearSTR As String
Dim MonthSTR As String
Dim DaySTR As String
Dim FixURL As String
Dim TargetFileName As String
Dim FSO As Object
Dim oApp As Object
Dim Fname As Variant
Dim DefPath As String
Dim strDate As String
Dim StrFile As String
Dim FileList(1 To 288) As String
Application.ScreenUpdating = False
FixURL = "http://www.nemweb.com.au/REPORTS/ARCHIVE/Dispatch_SCADA PUBLIC_DISPATCHSCADA_"
WantedID = Range(Cells(2, 1), Cells(8, 1))
YearNUM = 2016
StarMonth = 12
EndMonth = 12
For YearNUM = 2015 To 2016
For MonthNUM = StarMonth To EndMonth
For DayNUM = 1 To 31
YearSTR = CStr(YearNUM)
If MonthNUM < 10 Then
MonthSTR = "0" & CStr(MonthNUM)
Else:
MonthSTR = CStr(MonthNUM)
End If
If DayNUM < 10 Then
DaySTR = "0" & CStr(DayNUM)
Else:
DaySTR = CStr(DayNUM)
End If
myURL = FixURL & YearSTR & MonthSTR & DaySTR & ".zip"
Cells(1, 1) = myURL
Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False
WinHttpReq.Send
myURL = WinHttpReq.ResponseBody
If WinHttpReq.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.ResponseBody
TargetFileName = "C:\Users\istvan.szabo\Documents \Basslink\AEMO RAW DATA\RAWRAW\" & YearSTR & MonthSTR & DaySTR & ".zip"
oStream.SaveToFile (TargetFileName)
oStream.Close
End If
'try unzippin'
Fname = TargetFileName
If Fname = False Then
'Do nothing
Else
'Root folder for the new folder.
'You can also use DefPath = "C:\Users\Ron\test\"
DefPath = Application.DefaultFilePath
If Right(DefPath, 1) <> "\" Then
DefPath = DefPath & "\"
End If
FileNameFolder = "C:\Users\istvan.szabo\Documents\Basslink\AEMO RAW DATA\RAWRAW\" & YearSTR & MonthSTR & DaySTR
'Make the normal folder in DefPath
MkDir FileNameFolder
'Extract the files into the newly created folder
Set oApp = CreateObject("Shell.Application")
oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items
On Error Resume Next
Set FSO = CreateObject("scripting.filesystemobject")
FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
i = 1
StrFile = Dir(FileNameFolder & "\")
Do While Len(StrFile) > 0
FileList(i) = FileNameFolder & "\" & StrFile
FileListCSV(i) = Left(StrFile, Len(StrFile) - 3) & "csv"
StrFile = Dir
i = i + 1
Loop
'unzip the unzipped
For i = 1 To 288
Fname = FileList(i)
If Fname = False Then
'Do nothing
Else:
DefPath = Application.DefaultFilePath
If Right(DefPath, 1) <> "\" Then
DefPath = DefPath & "\"
End If
FileNameFolder = "C:\Users\istvan.szabo\Documents\Basslink\AEMO RAW DATA\"
Set oApp = CreateObject("Shell.Application")
oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items
On Error Resume Next
Set FSO = CreateObject("scripting.filesystemobject")
FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
Call OpenSearch
End If
Next i
End If
Next DayNUM
Next MonthNUM
StarMonth = 1
EndMonth = 5
Next YearNUM
Application.ScreenUpdating = True
End Sub
You could check the file without opening it. That would save you time and resources. Here is a quick draw of the code I would use:
Sub OpenSearch()
Dim ROW, j As Integer
Dim fileID
Dim buf As String
Dim tmp As Variant
Open FileNameFolder & FileListCSV(i) For Input As #1
For j = 1 To 7
ROW = 3
Do Until EOF(1)
Line Input #1, buf
'Remove double quotes
buf = Replace(buf, """", "")
'Split line to a array
tmp = Split(buf, ",")
'5 is the 6th column in excel tmp index starts with 0
fileID = tmp(5)
If fileID = WantedID(j, 1) Then
MsgBox "WE HAVE A MATCH!"
End If
ROW = ROW + 1
Loop
Next j
Close #1
Kill FileNameFolder & FileListCSV(i)
End Sub
EDIT: Also try to add a resource cleanup code, for example: Set WinHttpReq = Nothing, Set oStream = Nothing etc.
In line with other advice in the comments: -
You should close of resources when you are done with them using Set WinHttpReq = Nothing for example. This can avoid memory problems that are similar to the issue you are seeing.
It is also advisable to remove On Error Resume Next. This is hiding errors and you may well be missing results that you need. It would also allow for more information during errors.
I took your two code blocks and wrote them into one that I believe will be stable during running and make it to the end, Run this and let us know if it did resolve the issue. I did it this way as there was a lot of small changes that went towards what I suspect will be more stable and make it to the end.
Sub DownloadandUnpackFile()
Dim FSO As New FileSystemObject
Dim DteDate As Date
Dim Fl As File
Dim Fl_Root As File
Dim Fldr As Folder
Dim Fldr_Root As Folder
Dim LngCounter As Long
Dim LngCounter2 As Long
Dim oApp As Object
Dim oStream As Object
Dim oWinHttpReq As Object
Dim RngIDs As Range
Dim StrURL As String
Dim StrRootURL As String
Dim VntFile As Variant
Dim VntFolder As Variant
Dim VntRootFile As Variant
Dim VntRootFolder As Variant
Dim WkBk As Workbook
Dim WkSht As Worksheet
'This will speed up processing, but you might not see progress while it is working
Application.ScreenUpdating = False
'Set variables
StrRootURL = "http://www.nemweb.com.au/REPORTS/ARCHIVE/Dispatch_SCADA/PUBLIC_DISPATCHSCADA_"
'You should be a little more explicit here for clarity, refernce a worksheet
'E.g. StrID = ThisWorkbook.Worksheets("Sheet1").Range(Cells(2, 1), Cells(8, 1))
Set RngIDs = Range(Cells(2, 1), Cells(8, 1))
Set oWinHttpReq = CreateObject("Microsoft.XMLHTTP")
Set oApp = CreateObject("Shell.Application")
'Loop from 21/Feb/2015 to today
For DteDate = CDate("21/Feb/2015") To Date
StrURL = StrRootURL & Format(DteDate, "YYYYMMDD") & ".zip"
Debug.Print StrURL
oWinHttpReq.Open "GET", StrURL, False
oWinHttpReq.Send
StrURL = oWinHttpReq.ResponseBody
If oWinHttpReq.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write oWinHttpReq.ResponseBody
VntRootFile = Environ("UserProfile") & "\Documents\Basslink\AEMO RAW DATA\RAWRAW\" & Format(DteDate, "YYYYMMDD") & ".zip"
oStream.SaveToFile VntRootFile
oStream.Close
Set oStream = Nothing
VntRootFolder = Environ("UserProfile") & "\Documents\Basslink\AEMO RAW DATA\RAWRAW\" & Format(DteDate, "YYYYMMDD") & "\"
FSO.CreateFolder VntRootFolder
oApp.Namespace(VntRootFolder).CopyHere oApp.Namespace(VntRootFile).Items
Set Fldr_Root = FSO.GetFolder(VntRootFolder)
'Unzip the zipped zips
For Each Fl_Root In Fldr_Root.Files
If Right(LCase(Fl_Root.Name), 4) = ".zip" Then
VntFolder = Fl_Root.ParentFolder & "\" & Left(Fl_Root.Name, Len(Fl_Root.Name) - 4) & "\"
FSO.CreateFolder VntFolder
VntFile = Fl_Root.Path
oApp.Namespace(VntFolder).CopyHere oApp.Namespace(VntFile).Items
Set Fldr = FSO.GetFolder(VntFolder)
For Each Fl In Fldr.Files
If Right(LCase(Fl.Name), 4) = ".csv" Then
Set WkBk = Application.Workbooks.Open(Fl.Path)
Set WkSht = WkBk.Worksheets(1)
For LngCounter = 1 To RngIDs.Rows.Count
LngCounter2 = 1
Do Until WkSht.Cells(LngCounter2, 6) = ""
If WkSht.Cells(LngCounter2, 6) = RngIDs.Cells(LngCounter, 1) Then
Debug.Print "FOUND: " & Fl.Name & ": " & WkSht.Cells(LngCounter2, 6).Address
End If
LngCounter2 = LngCounter2 + 1
Loop
Next
Set WkSht = Nothing
WkBk.Close 0
Set WkBk = Nothing
End If
DoEvents
Next
Set Fldr = Nothing
End If
Next
Fldr_Root.Delete True
Set Fldr_Root = Nothing
FSO.DeleteFile VntRootFile, True
End If
DoEvents
Next
Set oApp = Nothing
Set oWinHttpReq = Nothing
Set RngIDs = Nothing
Application.ScreenUpdating = True
End Sub
Changes I have made: -
I used early binding to FileSystemObject simply to make it easier
to write up. You will need the 'Windows Scripting Runtime' reference
added (Tools > References > tick 'Windows Scripting Runtime')
I iterated through dates as a single loop rather then three loops of
strings working as a date
I set IDs to be a range and note a variant
I opened references once, reuse them (i.e. oApp), and then close
them
I added DoEvents to give time back to the computer to run anything it
may need to, this maintains a health system.
I used Debug.Print to add information to the immediate window instead
of msgbox, but you should really list the finds out in a separate
worksheet, (debug.print has a size limit so you may end up only
seeing X number of results as others are truncated off.