VBA is NOT cooperating with me I think something is wrong with Excel
After messing around with the code for several hours I've boiled it down to this:
Code: Select all
Sub Workbook()
Dim myWorkbook As Workbooks
Set myWorkbook = ActiveWorkbook
With myWorkbook
'actions here
End With
End Sub
So that won't work. Is there a way to fix this? Help!
The complete code is here:
Code: Select all
Sub openAllfilesInALocation()
Dim i As Integer, wb As Workbook
Dim Val1 As Integer
Dim Val2 As Integer
Dim Val3 As Integer
Dim Val4 As Integer
Dim Val5 As Integer
Dim Val6 As Integer
With Application.FileSearch
.NewSearch
.LookIn = "C:\myexcel"
.SearchSubFolders = False
.Filename = "*.xls"
.Execute
For i = 1 To .FoundFiles.Count
MsgBox (.FoundFiles(i))
Workbooks.Open (.FoundFiles(i))
wb = Workbooks(Filename:=.FoundFiles(i))
'Open each workbook
MsgBox ("this does not work")
'Perform the operation on the open workbook
'Val1 = Val1 + Workbooks(.FoundFiles(i)).Worksheets(1).Range("E6")
'Val2 = Val2 + wb.Worksheets(1).Range("E7")
'Val3 = Val3 + wb.Worksheets(1).Range("E8")
'Val4 = Val4 + wb.Worksheets(1).Range("E9")
'Val5 = Val5 + wb.Worksheets(1).Range("E10")
'Val6 = Val6 + wb.Worksheets(1).Range("E11")
'Save and close the workbook
wb.Close
'On to the next workbook
MsgBox ("runs")
Next i
End With
MsgBox ("Does run!")
ThisWorkbook.Worksheets(1).Range("A1").Value = Val1
ThisWorkbook.Worksheets(1).Range("A2").Value = Val2
ThisWorkbook.Worksheets(1).Range("A3").Value = Val3
ThisWorkbook.Worksheets(1).Range("A4").Value = Val4
ThisWorkbook.Worksheets(1).Range("A5").Value = Val5
ThisWorkbook.Worksheets(1).Range("A6").Value = Val6
End Sub
Argh, I got it, finally
Code: Select all
Sub openAllfilesInALocation()
Dim i As Integer, wbOpened As Workbook, wsOpened As Worksheet
Dim Val1 As Integer
Dim Val2 As Integer
Dim Val3 As Integer
Dim Val4 As Integer
Dim Val5 As Integer
Dim Val6 As Integer
With Application.FileSearch
.NewSearch
.LookIn = "C:\myexcel"
.SearchSubFolders = False
.Filename = "*.xls"
.Execute
For i = 1 To .FoundFiles.Count
'Open each workbook
Set wbOpened = Workbooks.Open(.FoundFiles(i))
Set wsOpened = wbOpened.Sheets(1)
'Perform the operation on the open workbook
'Val1 = Val1 + wbOpened.Worksheets(1).Range("E6")
Val1 = Val1 + wsOpened.Range("E6")
Val2 = Val2 + wsOpened.Range("E7")
Val3 = Val3 + wsOpened.Range("E8")
Val4 = Val4 + wsOpened.Range("E9")
Val5 = Val5 + wsOpened.Range("E10")
Val6 = Val6 + wsOpened.Range("E11")
'Save and close the workbook
wbOpened.Close
'On to the next workbook
Next i
End With
ThisWorkbook.Worksheets(1).Range("A1").Value = Val1
ThisWorkbook.Worksheets(1).Range("A2").Value = Val2
ThisWorkbook.Worksheets(1).Range("A3").Value = Val3
ThisWorkbook.Worksheets(1).Range("A4").Value = Val4
ThisWorkbook.Worksheets(1).Range("A5").Value = Val5
ThisWorkbook.Worksheets(1).Range("A6").Value = Val6
End Sub