VBA, Error 9 Wheres the error? - vba

Sub NapiMaker()
Dim wb As Workbook
Set wb = ActiveWorkbook
Debug.Print wb.Name
Dim MyFile As String
If MyFile = "" Then
MyFile = Application.GetOpenFilename()
Workbooks.Open (MyFile)
wb.Activate
Dim WS_Count As Integer
Dim I As Integer
WS_Count = wb.Worksheets.Count
For I = 1 To WS_Count
wb.Worksheets(I).Range("B7").Copy Workbooks(MyFile).Worksheets(1).Range("A16")
wb.Worksheets(I).Range("B8").Copy Workbooks(MyFile).Worksheets(1).Range("B16")
wb.Worksheets(I).Range("B10").Copy Workbooks(MyFile).Worksheets(1).Range("D16")
wb.Worksheets(I).Range("B11").Copy Workbooks(MyFile).Worksheets(1).Range("J16")
wb.Worksheets(I).Range("B5").Copy Workbooks(MyFile).Worksheets(1).Range("F16")
wb.Worksheets(I).Range("B14").Copy Workbooks(MyFile).Worksheets(1).Range("E16")
Workbooks(MyFile).Worksheets("1").Range("A16").EntireRow.Insert
Next I
End If
End Sub
I want to the the following:
- I open a file.
- Press CRTL+K.
- Lets me choose a file.
- Copy the specified cells to the chosen file.
I can't find the problem.
It's under the For loop

The filename passed as an index to the Workbooks collection appears to not allow the path to be included. (I was sure I had seen somewhere that it could be.) Therefore Workbooks("abcdef.xlsx") would work, but Workbooks("C:\Temp\abcdef.xlsx") will not.
The following code will assign a Workbook object to the opened workbook, and then use that object to refer to it in subsequent statements, therefore avoiding the need to use an index into the Workbooks collection.
Sub NapiMaker()
Dim wb As Workbook
Dim wb1 As Workbook
Set wb = ActiveWorkbook
Debug.Print wb.Name
Dim MyFile As String
If MyFile = "" Then ' myFile will always be blank at this point
MyFile = Application.GetOpenFilename()
Set wb1 = Workbooks.Open(MyFile)
Dim WS_Count As Integer
Dim I As Integer
WS_Count = wb.Worksheets.Count
For I = 1 To WS_Count
wb.Worksheets(I).Range("B7").Copy wb1.Worksheets(1).Range("A16")
wb.Worksheets(I).Range("B8").Copy wb1.Worksheets(1).Range("B16")
wb.Worksheets(I).Range("B10").Copy wb1.Worksheets(1).Range("D16")
wb.Worksheets(I).Range("B11").Copy wb1.Worksheets(1).Range("J16")
wb.Worksheets(I).Range("B5").Copy wb1.Worksheets(1).Range("F16")
wb.Worksheets(I).Range("B14").Copy wb1.Worksheets(1).Range("E16")
'Changed "1" to 1
wb1.Worksheets(1).Range("A16").EntireRow.Insert
Next I
End If
End Sub

Related

How to use worksheet names as variables in Excel VBA

I am trying to write a macro that will prompt the user to open 2 workbooks and then loop through the worksheets in the 2 books comparing their contents and highlighting any differences in yellow. Each piece seems to be working on its own, but I cannot figure out how to set the workbook names as global variables to be used between the functions in my sub. Any help would be appreciated! :)
Public strFile1 As String
Public strFile2 As String
Public wbSource1 As Workbook
Public wbSource2 As Workbook
Public I As Integer
Sub DifferenceCheckBetweenBooks()
Call openIt
Call WorksheetLoop
End Sub
Function openIt()
strFile1 = Application.GetOpenFilename
Workbooks.Open strFile1
Set wbSource1 = Workbooks.Open(strFile1)
strFile2 = Application.GetOpenFilename
Workbooks.Open strFile2
Set wbSource2 = Workbooks.Open(strFile2)
End Function
Function WorksheetLoop()
Dim WS_Count As Integer
WS_Count = Workbooks(wbSource1).Worksheets.Count
' Begin the loop.
For I = 1 To WS_Count
Call compareBooks
Next I
End Function
Function compareBooks()
Dim mycell As Range
'For each cell in worksheet that is not the same as compared worksheet, color it yellow
For Each mycell In Workbooks(wbSource1).Worksheets(I).UsedRange
If Not mycell.Value = Workbooks(wbSource2).Worksheets(I).Cells(mycell.Row, mycell.Column).Value Then
mycell.Interior.Color = vbYellow
Workbooks(wbSource2).Worksheets(I).Cells(mycell.Row, mycell.Column).Interior.Color = vbYellow
End If
Next
Workbooks(wbSource2).Worksheets(I).Select
End Function
I am getting the classic "subscript out of range error" which points to my wbSource1 variable as empty.
Don't do this
Workbooks.Open strFile1
Set wbSource1 = Workbooks.Open(strFile1)
you only need
Set wbSource1 = Workbooks.Open(strFile1)
And as SJR points out:
WS_Count = wbSource1.Worksheets.Count 'plus all other instances of this
You should really refactor your code to remove the globals and use parameters in your methods instead - that's a much safer approach.
Refactored to remove globals:
Sub DifferenceCheckBetweenBooks()
Dim wb1 As Workbook, wb2 As Workbook
Set wb1 = OpenIt("Choose first file")
If wb1 Is Nothing Then Exit Sub
Set wb2 = OpenIt("Choose second file")
If wb2 Is Nothing Then Exit Sub
CompareWorkbooks wb1, wb2
End Sub
Sub CompareWorkbooks(wb1 As Workbook, wb2 As Workbook)
Dim i As Long, sht1 As Worksheet, sht2 As Worksheet, c As Range, c2 As Range
For i = 1 To wb1.Worksheets.Count
Set sht1 = wb1.Worksheets(i)
Set sht2 = wb2.Worksheets(i)
For Each c In sht1.UsedRange.Cells
Set c2 = sht2.Range(c.Address)
If c.Value <> c2.Value Then
c.Interior.Color = vbYellow
c2.Interior.Color = vbYellow
End If
Next c
Next i
End Sub
Function OpenIt(msg As String) As Workbook
Dim strFile
strFile = Application.GetOpenFilename(Title:=msg)
If Len(strFile) > 0 Then Set OpenIt = Workbooks.Open(strFile)
End Function

Copy all sheets from a targeted workbook

I am getting run-time error '2147 and for the life of me I can't see what I am missing.
All I am trying to do is from my current workook open a selected workbook and copy in all sheets.
Thank you.
Sub GetFile()
Dim fNameAndPath As Variant
Dim wb As Workbook, wb2 As Workbook
Dim Ws As Worksheet
fNameAndPath = Application.GetOpenFilename(FileFilter:="Excel Files (*.XLS), *.XLS", Title:="Select File To Be Opened")
If fNameAndPath = False Then Exit Sub
Workbooks.Open Filename:=fNameAndPath
Application.ScreenUpdating = False
Set wb = ActiveWorkbook
Set wb2 = Workbooks.Add(fNameAndPath)
For Each Ws In wb2.Worksheets
Ws.Copy After:=wb.Sheets(wb.Sheets(1))
Next Ws
Application.ScreenUpdating = True
End Sub
Public Sub this()
Dim path As String, fileName As String
Dim sheet As Worksheet, thisWB As Workbook, thatWB As Workbook
Dim arr() As Variant
Dim rowC As Long, colC As Long
path = "C:\Users\dcoats\Desktop" & "\"
fileName = Dir(path & "*.xl??")
Set thisWB = ThisWorkbook
Do While Len(fileName) > 0
Set thatWB = Workbooks.Open(path & fileName, True, True)
For Each sheet In thatWB.Sheets
arr = sheet.UsedRange
rowC = sheet.UsedRange.Rows.Count
colC = sheet.UsedRange.Columns.Count
thisWB.Sheets.Add After:=Worksheets(Worksheets.Count)
thisWB.ActiveSheet.Range(thisWB.ActiveSheet.Cells(1, 1), thisWB.ActiveSheet.Cells(rowC, colC)).Value2 = arr
Next sheet
thatWB.Close False
fileName = Dir()
Loop
End Sub
This should work for you. Careful though it loops through all files in a directory (sorry I basically copied/pasted this from a script library i keep).

Subscript out of range error VBA when copying multiple sheets

I have a VBA function that I am using to copy of list of sheets from active workbook and save it. I am getting subscript out of range error. Any help would be appreciated?
Private Sub exporttoexcel(excelFileName)
excelFileName = 'File in my local'
Dim mySheetList() As String
Dim WS As Worksheets
Dim WB As Workbook
MsgBox excelFileName
'Dim sourceWB As Workbook
'Dim destWB As Workbook
'
'Set sourceWB = ActiveWorkbook
'sourceWB.Sheets.Copy
'
'Set WB = Workbooks(excelFileName)
ReDim mySheetList(0 To (ThisWorkbook.Sheets.Count) - 1)
Dim a As Integer
a = 0
For Each WS In ActiveWorkbook.Worksheets
mySheetList(a) = WS.Name
a = a + 1
Next
Dim Fileobj
Set Fileobj = CreateObject("Scripting.FileSystemObject")
If Fileobj.FileExists(excelFileName) Then
Fileobj.DeleteFile excelFileName
End If
' 'actually save
Worksheets(mySheetList).Copy '<<<<<<< RUN-TIME ERROR 9 RAISED HERE
ActiveWorkbook.SaveAs FileName:=excelFileName
'MsgBox excelFileName
'ThisWorkbook.SaveAs FileName:=excelFileName, FileFormat:=xlXMLSpreadsheet
Application.Wait (Now + TimeValue("0:00:15"))
WB.Close
End Sub
I think you have passed the sheet a list of names of sheets, i.e., "sheet1","sheet2",etc. However, when passing an array the function Sheets(Array(mySheetList)) must be used.
'Worksheets(mySheetList).Copy
Sheets(Array(mySheetList)).Copy
This works for me, I would try adapting somewhat for your excelfilename. There was also a problem with the ws being dimmed as a worksheet. I would use Option Explicit in the future.
Private Sub exporttoexcel()
'excelFileName = 'File in my local'
Dim mySheetList() As String
Dim WS
Dim WB As Workbook
MsgBox excelFileName
'Dim sourceWB As Workbook
'Dim destWB As Workbook
'
'Set sourceWB = ActiveWorkbook
'sourceWB.Sheets.Copy
'
'Set WB = Workbooks(excelFileName)
ReDim mySheetList(0 To (ThisWorkbook.Sheets.count) - 1)
Dim a As Integer
a = 0
For Each WS In ThisWorkbook.Worksheets
mySheetList(a) = WS.Name
a = a + 1
Next
Dim Fileobj
Set Fileobj = CreateObject("Scripting.FileSystemObject")
If Fileobj.FileExists(excelFileName) Then
Fileobj.DeleteFile excelFileName
End If
' 'actually save
Sheets(mySheetList).Copy
ActiveWorkbook.SaveAs Filename:=excelFileName
'MsgBox excelFileName
'ThisWorkbook.SaveAs FileName:=excelFileName, FileFormat:=xlXMLSpreadsheet
Application.Wait (Now + TimeValue("0:00:15"))
WB.Close
End Sub

Compare two workbook sheets excel vba

I am working on a excel newly jfor 1 weeks where i want to compare opened excel file current open file,
I made all possible but whenever I try to read the row, it only reading the value from the opened , I cant' able to access to read current workbook where i my macro was coded
Sub test1()
Dim iComp
Dim sheet As String
Dim wbTarget As Worksheet
Dim wbThis As Worksheet
Dim bsmWS As Worksheet
Dim c As Integer
Dim x As Integer
Dim strValue As String
Static value As Integer
Dim myPath As String
Dim folderPath As String
k = 3
Filename = Application.GetOpenFilename("Excel files (*.xls*),*.xl*", Title:="Open data") ' Choosing the Trigger Discription
'Set wbTarget = ActiveWorkbook.ActiveSheet
Set theRange = Range("A2:A4")
c = theRange.Rows.Count
strValue = vbNullString
For x = 1 To c
strValue = strValue & theRange.Cells(x, 1).value
Next x
'Set tabWS = Sheets("Tabelle1")
folderPath = Application.ActiveWorkbook.Path
myPath = Application.ActiveWorkbook.FullName
Set bsmWS = Sheets("Tabelle1")
Set wbkA = Workbooks.Open(Filename:="myPath")
Set varSheetA = wbkA.Worksheets("Balance sheet").Range(strRangeToCheck)
Its a 1000 line code , I just put only snippet.
I have myworksheet in the workbook where I am programed . I want to open another worksheet, take the value and compare it with my current worksheet . If string matches (ex range (A1:A2)) then msgbox yes
Have you tried using ThisWorkbook.Sheets("sheet name").Range("A2:A4") or ThisWorkbook.ActiveSheet.Range("A2:A4"). This will ensure the reference is to the workbook where the code is located.
More info on Application.ThisWorkbook
https://msdn.microsoft.com/en-us/library/office/ff193227.aspx.

Copy Range from multiple workbooks in folder to Summary Workbook also in folder?

I have a folder with 100+ workbooks. These workbooks contain a range of data. For simplicity I will call the data range A1:D2, the range is located on Sheet1 of all 100+ workbooks.
I also have a Summary workbook.
I would like to place VBA code in the Summary workbook that loops through the folder, copying the range A1:D2 of each of the 100+ workbooks.
I would then like to paste the A1:D2 range from each workbook in to Sheet1 of the Summary workbook. Each paste will start on the next unused row.
I am stuck doing this via a manual process right now and it is driving me insane.
I do know some basic VBA coding however my problem is that I can't figure out how to loop it correctly, and I am stuck coding each individual workbook to open-->copy-->paste-->close. This was fine with 10-20 workbooks but now I am at 100+ and it is growing every week.
Thanks again,
Brian
I have something that does exactly what you are asking for, if you want to copy multiple workbooks I suggest creating a new worksheet to capture the workbook information onto a spreadsheet. Instructions below
Create a new worksheet and give it a name, in this case we'll call the sheet 'Control'
Create a new module in VBA and use the code below to operate the workbook copy
I have left a section out for you to write your code for the functions that you want to perform.
Sub WorkbookConsolidator()
Dim WB As Workbook, wb1 as workbook
Dim WBName as Range
Dim folderselect as Variant, wbA as Variant, wbB as Variant,
Dim I as long, J as long
Dim objFolder As Object, objFile As Object
Dim WBRange as String
'Set Core Variables and Open Folder containing workbooks.
Set WB = ThisWorkbook
Worksheets("Control").Activate
Set FolderSelect = Application.FileDialog(msoFileDialogFolderPicker)
FolderSelect.AllowMultiSelect = False
MsgBox ("Please Select the Folder containing your Workbooks")
FolderSelect.Show
WBRange = FolderSelect.SelectedItems(1)
Set objFolder = objFSO.GetFolder(FolderSelect.SelectedItems(1))
' Fill out File name Fields in Control Sheet
' The workbook names will be captured in Column B
' This allows allocation for up to 100 workbooks
For I = 1 To 100
For Each objFile In objFolder.files
If objFile = "" Then Exit For
Cells(I, 2) = objFile.Name ' Workbook Name
Cells(I, 3) = WBRange ' Workbook Path
I = I + 1
Next objFile
Next I
'Loop through the list of workbooks created in the 'Control' Directory, adjust the loop range as preferred
For J = 100 To 1 Step -1
With Workbooks(ThisWorkbook).Worksheets("Control")
BookLocation = .Range("C" & J).Value
BookName = .Range("B" & J).Value
End With
Set wb1 = Workbooks.Open(Booklocation & Bookname)
' Write your code here'
CleanUp:
wb1.Close SaveChanges:=False
Next J
End Sub()
`
Try this
Sub combine_into_one()
Dim FSO As Object: Set FSO = CreateObject("Scripting.FileSystemObject")
Dim strPath$, Pivot$, sUserName$, sFolderName$, sSourceName$, x&
Dim oFldialog As FileDialog
Dim oFile As Scripting.File
Dim oFolder
Set oFldialog = Application.FileDialog(msoFileDialogFolderPicker)
With oFldialog
If .Show = -1 Then
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strPath
sFolderName = .SelectedItems(1)
End If
End With
Set oFolder = FSO.GetFolder(sFolderName)
Workbooks.Add: Pivot = ActiveWorkbook.Name 'Destination workbook
For Each oFile In oFolder.Files
Workbooks(Pivot).Activate
x = Workbooks(Pivot).Sheets("Sheet1").Cells.SpecialCells(xlCellTypeLastCell).Row + 1
Workbooks.Open filename:=oFile: sSourceName = ActiveWorkbook.Name
Workbooks(sSourceName).Activate
Workbooks(sSourceName).Sheets("Sheet1").[A1:D1].Copy
Workbooks(Pivot).Activate
Workbooks(Pivot).Sheets("Sheet1").Cells(x, 1).PasteSpecial xlPasteAll
Workbooks(sSourceName).Close False
Next
End Sub