I have 2 Excel workbooks. Both are in different folders.
I am copying data from one to another using a macro.
I observe a subscript out of range error...
Any insights in to this ?
Here is my code
Sub copydata()
Dim wkbSource As Workbook
Dim wkbDest As Workbook
Dim shttocopy As Worksheet
Dim wbname As String
' check if the file is open
ret = Isworkbookopen("C:\file1.xlsx")
If ret = False Then
' open file
Set wkbSource = Workbooks.Open("C:\file1.xlsx")
Else
'Just make it active
Workbooks("C:\file1.xlsx").Activate
End If
' check if the file is open
ret = Isworkbookopen("C:\File2.xlsx")
If ret = False Then
' open file
Set wkbDest = Workbooks.Open("C:\file2.xlsx")
Else
'Just make it active
Workbooks("file2.xlsx").Activate
End If
'perform copy
Set shttocopy = wkbSource.Sheets("filedata")
shttocopy.Copy wkbDest.Sheets(3)
End Sub
Function Isworkbookopen(filename As String)
Dim ff As Long, ErrNo As Long
Dim wkb As Workbook
Dim nam As String
wbname = filename
On Error Resume Next
ff = FreeFile()
Open filename For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: Isworkbookopen = False
Case 70: Isworkbookopen = True
Case Else: Error ErrNo
End Select
End Function
OK, I think I got it. Instead of .Activate, we'll just set the book if it's already open. We'll also reference the book by its file name, NOT path (as I had erroneously suggested in a comment above).
This worked for me:
Sub copydata()
Dim wkbSource As Workbook
Dim wkbDest As Workbook
Dim shttocopy As Worksheet
Dim wbname As String
' check if the file is open
ret = Isworkbookopen("C:\stack\file1.xlsx")
If ret = False Then
' open file
Set wkbSource = Workbooks.Open("C:\stack\file1.xlsx")
Else
'Just make it active
'Workbooks("C:\stack\file1.xlsx").Activate
Set wkbSource = Workbooks("file1.xlsx")
End If
' check if the file is open
ret = Isworkbookopen("C:\stack\File2.xlsx")
If ret = False Then
' open file
Set wkbDest = Workbooks.Open("C:\stack\file2.xlsx")
Else
'Just make it active
'Workbooks("C:\stack\file2.xlsx").Activate
Set wkbDest = Workbooks("file2.xlsx")
End If
'perform copy
Set shttocopy = wkbSource.Sheets("filedata")
shttocopy.Copy wkbDest.Sheets(3)
End Sub
Function Isworkbookopen(filename As String)
Dim ff As Long, ErrNo As Long
Dim wkb As Workbook
Dim nam As String
wbname = filename
On Error Resume Next
ff = FreeFile()
Open filename For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: Isworkbookopen = False
Case 70: Isworkbookopen = True
Case Else: Error ErrNo
End Select
End Function
Sub CopyData()
Dim Book As Workbook ' probably not needed
Set destinationFile = ThisWorkbook ' probably not needed
sourceFile = ("Add your source file name")
sourceFileLocation = ("add your source file location")
Workbooks.Open (sourceFileLocation + "\" + sourceFile)
Windows(sourceFile).Activate
Range("A1:X7215").Select 'Range Values can be changed depending upon the size of the data (total number of records and columns)
Selection.Copy
destinationFile.Activate
ActiveSheet.Paste
Application.CutCopyMode = False
ActiveWorkbook.Save
Windows(sourceFile).Activate
ActiveWindow.Close
End Sub
Related
Thanks a lot for your help! Unfortunately, I tested you code and I got the following error message: Run time error 9 Subscript out of range
It seems in fact that this line causes a problem: Set wbThis = ThisWorkbook Due to this problem, it seems that "Sheet1" is not recognized in my current workbook (I checked it via a debug print in my immediate window), I consulted this topic: Subscript out of range when referencing a worksheet in another workbook from a variable. That is why I modified "Set wbThis = ThisWorkbook" by "Set wbThis = ActiveWorkbook" After doing this modification and executing my macro (this time I do not get any error message), the excel file "Parc Vehicule Template.xls" is open but the instruction rng.Copy wsThat.Range("A1") is not executed, It means that my datas are not copied yet from my initial workbook open to my other workbook "Parc Vehicule Template.xls"
Thank you so much In advance for your help. Xavi
Set your objects and then work with them. Your life will become very easy. If I was to do the same thing, I would do it this way...
Is this what you are trying? (UNTESTED)
Sub copysheet1tofileParcVehiculeTemplatefortherest()
Dim wbThis As Workbook, wbThat As Workbook
Dim wsThis As Worksheet, wsThat As Worksheet
Dim rng As Range
Dim fName As String
Set wbThis = ThisWorkbook
Set wsThis = wbThis.Sheets("Sheet1")
Set rng = wsThis.Range("A1:AZ10000")
fName = "\\ingfs05\data1\GBS Center \52 Migration\ Files\Parc auto Template.xls"
If Not IsWorkBookOpen(fName) Then
Set wbThat = Workbooks.Open(fName)
Set wsThat = wbThat.Sheets("PV template for the rest")
rng.Copy wsThat.Range("A1")
End If
End Sub
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
Also I see that Fname and Workbooks("Parc Vehicule Template.xls") are different. If that is intentional then I guess you are trying this?
Sub copysheet1tofileParcVehiculeTemplatefortherest()
Dim wbThis As Workbook, wbThat As Workbook, wbTmplt As Workbook
Dim wsThis As Worksheet, wsThat As Worksheet
Dim rng As Range
Dim fName As String
Set wbThis = ThisWorkbook
Set wsThis = wbThis.Sheets("Sheet1")
Set rng = wsThis.Range("A1:AZ10000")
fName = "\\ingfs05\data1\GBS Center \52 Migration\ Files\Parc auto Template.xls"
If Not IsWorkBookOpen(fName) Then
Set wbTmplt = Workbooks.Open(fName)
Set wbThat = Workbooks("Parc Vehicule Template.xls")
Set wsThat = wbThat.Sheets("PV template for the rest")
rng.Copy wsThat.Range("A1")
End If
End Sub
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
I have written this sort of code in VBA:
Sub itemselecter()
Dim Filename1 As String
Dim Sourcewb1 As Workbook
Dim Targetwb1 As Workbook
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
If .Show = 0 Then
Exit Sub
Else
Filename1 = .SelectedItems(1)
Err.Clear
On Error GoTo 0
End If
End With
Application.ScreenUpdating = False
Set Sourcewb1 = Workbooks.Open(Filename1) 'Open FIC data
Set Targetwb1 = ThisWorkbook
Targetwb1.Worksheets("Data").ClearContents
Sourcewb1.Worksheets(1).Cells.Copy Destination:=Targetwb.Sheets("Data").Cells
Sourcewb1.Close (False)
Application.ScreenUpdating = True
End Sub
It gives me at the moment error 424, while trying to select the file from documents. What is wrong?
Try the code below, check for comments inside the code where I've made modifications.
If you would have added Option Explicit at the top of your code, then the second error wouldn't have occurred (where you mixed-up Targetwb with Targetwb1).
Code
Option Explicit
Sub itemselecter()
Dim Filename1 As String
Dim Sourcewb1 As Workbook
Dim Targetwb1 As Workbook
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
If .Show = 0 Then
Exit Sub
Else
Filename1 = .SelectedItems(1)
Err.Clear
On Error GoTo 0
End If
End With
Application.ScreenUpdating = False
Set Sourcewb1 = Workbooks.Open(Filename1) 'Open FIC data
Set Targetwb1 = ThisWorkbook
Targetwb1.Worksheets("Data").Cells.ClearContents '<-- added .Cells to clear the worksheet's entire cells contents
Sourcewb1.Worksheets(1).Cells.Copy Destination:=Targetwb1.Sheets("Data").Cells '<-- need to be Targetwb1 not Targetwb
Sourcewb1.Close (False)
Application.ScreenUpdating = True
End Sub
Kindly change this line of code,
Targetwb1.Worksheets("Data").ClearContents
into something like
Targetwb1.Sheets("Data").Cells.ClearContents
Please let me suggest you to check if the sheet "Data" exists in that workbook.
I am using a VBA script where the first worksheets of all workbooks saved in a specific folder are consolidated in one workbook. What I want is, if any source workbook is open while running this script, then I should get a prompt that 'source workbook is open' and the script should not run.
VBA script of destination worksheet is as follows:
Private Sub CommandButton1_Click()
Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
Dim WrdArray() As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
directory = "C:\test\"
fileName = Dir(directory & "*.xl??")
Application.EnableEvents = False
Do While fileName <> ""
Workbooks.Open (directory & fileName)
WrdArray() = Split(fileName, ".")
For Each sheet In Workbooks(fileName).Worksheets
Workbooks(fileName).ActiveSheet.Name = WrdArray(0)
total = Workbooks("import-sheets.xlsm").Worksheets.Count
Workbooks(fileName).Worksheets(sheet.Name).Copy After:=Workbooks("import-sheets.xlsm").Worksheets(total)
GoTo exitFor:
Next sheet
exitFor:
Workbooks(fileName).Close
fileName = Dir()
Loop
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
I appreciate your help in advance
Untested but it should work, source:
https://support.microsoft.com/en-us/kb/291295
Function IsFileOpen(filename As String)
Dim filenum As Integer, errnum As Integer
On Error Resume Next ' Turn error checking off.
filenum = FreeFile() ' Get a free file number.
' Attempt to open the file and lock it.
Open filename For Input Lock Read As #filenum
Close filenum ' Close the file.
errnum = Err ' Save the error number that occurred.
On Error GoTo 0 ' Turn error checking back on.
' Check to see which error occurred.
Select Case errnum
' No error occurred.
' File is NOT already open by another user.
Case 0
IsFileOpen = False
' Error number for "Permission Denied."
' File is already opened by another user.
Case 70
IsFileOpen = True
' Another error occurred.
Case Else
Error errnum
End Select
End Function
if you want to check if a workbook (an Excel file) is opened, try this function.
Public Function isWbOpened(ByVal wb As String) As Boolean
Dim workB As Workbook
isWbOpened = False
For Each workB In Workbooks
If workB.FullName = wb Or workB.Name = wb Then ''FullName : path + filename Name : filename only
isWbOpened = True
End If
Next workB
End Function
if the function return TRUE, then the Excel file is open, so skeep your script.
example:
if isWbOpened("theExcelFile.xlsx") then
msgbox "theExcelFile.xlsx is open"
end if
You can enumerate the files in a folder then test them to see if any is open before proceeding. Please note - the following code is assuming you are the one with them open, so if a shared file is open this may have to be adapted
Sub TestFolder()
Debug.Print XLFileIsOpen("C:\Test")
End Sub
Function XLFileIsOpen(sFolder As String) As Boolean
For Each Item In EnumerateFiles(sFolder)
If IsWorkBookOpen(CStr(Item)) = True Then XLFileIsOpen = True
Next Item
End Function
Function EnumerateFiles(sFolder As String) As Variant
Dim objFSO As Object: Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objFolder As Object: Set objFolder = objFSO.GetFolder(sFolder)
Dim objFile As Object, V() As String
For Each objFile In objFolder.Files
If IsArrayAllocated(V) = False Then
ReDim V(0)
Else
ReDim Preserve V(UBound(V) + 1)
End If
V(UBound(V)) = objFile.Name
Next objFile
EnumerateFiles = V
End Function
Function IsArrayAllocated(Arr As Variant) As Boolean
On Error Resume Next
IsArrayAllocated = IsArray(Arr) And Not IsError(LBound(Arr, 1)) And LBound(Arr, 1) <= UBound(Arr, 1)
End Function
Function IsWorkBookOpen(sFile As String) As Boolean
On Error Resume Next
IsWorkBookOpen = Len(Application.Workbooks(sFile).Name) > 0
End Function
I have a problem that I need help to solve. I want to import a text file to a new temporary sheet, find some data, put them in my current sheet and then close the new temporary sheet. Is this possible and how do I do this?
To create a new Worksheet, then remove it:
Option Explicit
Sub openWorkSheet()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets.Add(, ThisWorkbook.ActiveSheet)
End Sub
Sub closeWorkSheet(ByRef ws As Worksheet)
If Not ws Is Nothing Then
With Application
.DisplayAlerts = False
ws.Delete
.DisplayAlerts = True
End With
End If
End Sub
To open a text file, read its contents and find specific strings:
Public Sub searchFile(ByVal filePathAndName As String)
Const TYPICAL_START = "FIRST search string"
Const TYPICAL_END = "LAST search string"
Dim fso As Object
Dim searchedFile As Object
Dim fullFile As String
Dim foundStart As Long
Dim foundEnd As Long
Dim resultArr() As String
Dim i As Long
Set fso = CreateObject("Scripting.FileSystemObject")
Set searchedFile = fso.OpenTextFile(filePathAndName)
fullFile = searchedFile.ReadAll 'read entire file
i = 1
foundStart = 1
foundStart = InStr(foundStart, fullFile, TYPICAL_START, vbTextCompare)
If foundStart > 0 Then
foundEnd = InStr(foundStart, fullFile, TYPICAL_END, vbTextCompare)
While foundStart > 0 And foundEnd > 0
ReDim Preserve resultArr(i)
resultArr(i) = Mid(fullFile, foundStart, foundEnd - foundStart + 1)
foundStart = InStr(foundStart + 1, fullFile, TYPICAL_START, vbTextCompare)
If foundStart > 0 Then foundEnd = InStr(foundStart, fullFile, TYPICAL_END)
i = i + 1
Wend
End If
End Sub
So now it shold work. This is the sub that does not want to work.
Sub Import()
Dim DestBook As Workbook, SourceBook As Workbook
Dim DestCell As Range
Dim RetVal As Boolean
' Set object variables for the active book and active cell.
Set DestBook = ActiveWorkbook
Set DestCell = ActiveCell
' Show the Open dialog box.
RetVal = Application.Dialogs(xlDialogOpen).Show("*.txt", , True)
' If Retval is false (Open dialog canceled), exit the procedure.
If RetVal = False Then Exit Sub
' Set an object variable for the workbook containing the text file.
Set SourceBook = ActiveWorkbook
' Copy the contents of the entire sheet containing the text file.
Range(Range("A1"), Range("A1").SpecialCells(xlLastCell)).Copy
' Activate the destination workbook and paste special the values
' from the text file.
DestBook.Activate
DestCell.PasteSpecial Paste:=xlValues
' Close the book containing the text file.
SourceBook.Close False
End Sub
I am trying to create a MS Word macro to check and see if a specific powerpoint file is open. If it is then I want it to go to next, but if not then open the file.
Public Sub CommandButton1_Click()
Dim pptApp As Object
Dim pptPres As String
'Dim nSlide As PowerPoint.Presentation
Dim folderPath, file As String
folderPath = ActiveDocument.Path & Application.PathSeparator
file = "Huntington_Template.pptx"
Set pptApp = CreateObject("PowerPoint.Application")
If pptApp.presentations(file).Enabled = True Then
GoTo cont
Else
pptApp.Visible = True
pptApp.presentations.Open (folderPath & file)
End If
cont:
End Sub
A minor variation of Steve's code, in case you want to not just test if the presentation is open, but also use it directly:
Function GetPowerpointFileIfOpen(pptApp As Object, sFullname As String) As Object
For Each p In pptApp.Presentations
If p.FullName = sFullname Then
Set GetPowerpointFileIfOpen = p
Exit Function
End If
Next p
End Function
And then you can test if the presentation is open - or open it otherwise:
Set ppt = GetPowerpointFileIfOpen(pptApp, sFullName)
If ppt Is Nothing Then
Set ppt = pptApp.Presentations.Open(sFullName, False)
End If
Add this to your module (aircode, may need debug help):
Function PPTFileIsOpen(pptApp as object, sFullname as string) as boolean
Dim x as long
For x = 1 to pptApp.Presentations.Count
if pptApp.Presentations(x).fullname = sFullname ) Then
PPTFileIsOpen = True
Exit Function
end if
Next
End Function
Then instead of your:
If pptApp.presentations(file).Enabled = True Then
use:
If Not PPTFileIsOpen(pptApp, folderPath & file) Then
' open the file as you're already doing
End If
I have used this function to determine if a workbook is already open it might work for powerpoint.
Public Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function
You can then call it by doing something like
Ret = IsWorkBookOpen("C:\Book1.xlsm")
If Ret = True Then
Set wb = Application.Workbooks("C:\Book1.xlsm")
wb.Activate
Else
Set wb = Application.Workbooks.Open("C:\Book1.xlsm")
End If