Wait until other users close the Excel file - excel

I have created a 'Login Tracker' system where 100 people all use an excel form saved to their computer, and when they hit "submit" it opens another .xlsb file(RTS Report) in a shared drive, finds the next line, and puts the data on the next line. This all takes 2-5 seconds to complete, however, if two people hit "submit" at the same time then one gets an error that the file is already open.
im new in vba please help me code for following scenarios
Check if Database.xlsb is open by another user
If not, continue with the code
If yes (file is not available) code need wait for until file close
Sub RTS()
ThisWorkbook.Activate
Application.DisplayAlerts = False
ActiveSheet.Range("A7:D7", "Q7").Select
Range("Q7").Activate
Application.CutCopyMode = False
Selection.Copy
Application.ScreenUpdating = False
Workbooks.Open Filename:="RTS Report.xlsx", ReadOnly:=False
Dim she As Worksheet
Dim a As Integer
ActiveWorkbook.Sheets("data").Activate
Set she = actveworkbook.actvesheet
b = she.Range("A" & Rows.Count).End(xlUp).Row
she.Range("A" & b + 1).PasteSpecial Paste:=xlPasteFormulasAndNumberFormats, operation:=xlNone, Skipblanks:=False, Transpose:=False
Cells.Select
Cells.EntireColumn.AutoFit
ActiveWorkbook.Save
Application.ScreenUpdating = True
ThisWorkbook.Activate
End Sub

As mentioned in the comments, excel is not ideal for this, but if is the only thing you have the following should work.
try to open until error disappears
Sub RTS()
ThisWorkbook.Activate
Application.DisplayAlerts = False
ActiveSheet.Range("A7:D7", "Q7").Select
Range("Q7").Activate
Application.CutCopyMode = False
Selection.Copy
Application.ScreenUpdating = False
cont = True
On Error Resume Next
While cont
Err.Clear
Workbooks.Open Filename:="RTS Report.xlsx", ReadOnly:=False
If Err.Number <> 0 Then
Application.Wait (Now + TimeValue("0:00:01"))
Err.Clear
Else
cont = False
End If
Wend
On Error GoTo 0
Dim she As Worksheet
Dim a As Integer
ActiveWorkbook.Sheets("data").Activate
Set she = actveworkbook.actvesheet
b = she.Range("A" & Rows.Count).End(xlUp).Row
she.Range("A" & b + 1).PasteSpecial Paste:=xlPasteFormulasAndNumberFormats, operation:=xlNone, Skipblanks:=False, Transpose:=False
Cells.Select
Cells.EntireColumn.AutoFit
ActiveWorkbook.Save
Application.ScreenUpdating = True
ThisWorkbook.Activate
End Sub

Sub RTS()
ThisWorkbook.Activate
Application.DisplayAlerts = False
ActiveSheet.Unprotect ("GLOLOGIN")
Application.ScreenUpdating = False
'Copy & Paste the data from " Scheduled Ad " sheet to "RTS Report.Xlsb" Sheet
ActiveSheet.Range("A7:D7", "Q7").Select
ActiveSheet.Range("A7:D7,Q7").Select
Range("Q7").Activate
Application.CutCopyMode = False
Selection.Copy
'RTS Report is not open then open the doc & pasete this data
cont = True
On Error Resume Next
While cont
Err.Clear
Dim wb As Workbook
Set wb = Workbooks.Open(Filename:="G:\PPR MUMBAI\Everythig Else\MIS\LILO\.Data\RTS Report.xlsx")
Do Until wb.ReadOnly = False
wb.Close
Application.Wait Now + TimeValue("00:00:01")
Set wb = Workbooks.Open(Filename:="G:\PPR MUMBAI\Everythig Else\MIS\LILO\.Data\RTS Report.xlsx")
Loop
If Err.Number <> 0 Then
Application.Wait (Now + TimeValue("0:00:01"))
Err.Clear
Else
cont = False
End If
Wend
On Error GoTo 0
Dim She As Worksheet
Dim b As Integer
ActiveWorkbook.Sheets("Data").Activate
Set She = ActiveWorkbook.ActiveSheet
b = She.Range("A" & Rows.Count).End(xlUp).Row
She.Range("A" & b + 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Cells.Select
Cells.EntireColumn.AutoFit
ActiveWorkbook.Save
ActiveWorkbook.Close
ThisWorkbook.Activate
ActiveSheet.Protect ("GLOLOGIN")
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

Related

While saving another workbook using VBA saving pop-up showing that workbook file path

When using VBA in master document, I need to copy & paste data from another workbook and save to that workbook. While saving saving pop-up showing file destination path but I don't want other users know the path.
Sub RTS()
ThisWorkbook.Activate
Application.DisplayAlerts = False
Application.ScreenUpdating = False
ActiveSheet.Range("A7:D7", "Q7").Select ActiveSheet.Range("A7:D7,Q7").Select Range("Q7").Activate Application.CutCopyMode = False Selection.Copy
on Error Resume Next While cont Err.Clear Dim wb As Workbook Set wb = Workbooks.Open(Filename:="RTS Report.xlsx") Do Until wb.ReadOnly = False wb.Close Application.Wait Now + TimeValue("00:00:01") Set wb = Workbooks.Open(Filename:="RTS Report.xlsx")
Loop
If Err.Number <> 0 Then Application.Wait (Now + TimeValue("0:00:01")) Err.Clear Else cont = False End If
Wend
On Error GoTo 0
Dim She As Worksheet Dim b As Integer ActiveWorkbook.Sheets("Data").Activate
Set She = ActiveWorkbook.ActiveSheet
b = She.Range("A" & Rows.Count).End(xlUp).Row
She.Range("A" & b + 1).PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone,
SkipBlanks:=False, Transpose:=False
Cells.Select Cells.EntireColumn.AutoFit
ActiveWorkbook.Save ActiveWorkbook.Close ThisWorkbook.Activate Application.ScreenUpdating = True Application.DisplayAlerts = True
End Sub
put before the save string
Application.DisplayAlerts=False
and delete "Application.DisplayAlerts = True"

Excel VBA will not close my opened workbook

I am pretty much new to VBA and have been trying to learn, with this I have created a code that opens another work book and combines all data to a database file and then copy this to my current open file, the problem I have is that it will not close the workbook and takes a long time doing so. Any ideas please?.
'''
Option Explicit
Sub GasStockReport()
Dim wb As String
Dim st As String
Dim path As String
path = "C:\Users\si2066\OneDrive - ENGIE\Desktop\MP Templates\MP - Stock Control\"
wb = "Gas Stock Take v2"
Workbooks.Open path & wb
Dim sh As Worksheet
Dim destsh As Worksheet
Dim Last As Long
Dim CopyRng As Range
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Application.DisplayAlerts = False
On Error Resume Next
ActiveWorkbook.Worksheets("Database").Delete
On Error GoTo 0
Application.DisplayAlerts = True
Set destsh = ActiveWorkbook.Worksheets.Add
destsh.Name = "Database"
For Each sh In ActiveWorkbook.Worksheets
If sh.Name <> destsh.Name Then
Last = GetLastRow(destsh, 1)
With sh
Set CopyRng = sh.Range("A2:K" & GetLastRow(sh, 1))
End With
If Last + CopyRng.Rows.Count > destsh.Rows.Count Then
MsgBox "There are not enough rows in the Destsh"
GoTo ExitTheSub
Else
CopyRng.Copy IIf(Last = 1, destsh.Cells(1, "b"), destsh.Cells(Last + 1, "b"))
End If
If Last = 1 Then
destsh.Cells(Last, "A").Resize(CopyRng.Rows.Count).Value = sh.Name
Else
destsh.Cells(Last + 1, "A").Resize(CopyRng.Rows.Count).Value = sh.Name
End If
End If
Next
ExitTheSub:
Application.Goto destsh.Cells(1)
destsh.Columns.AutoFit
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
Range("A1").Select
Range(Selection, ActiveCell.End(xlDown).End(xlToRight)).Select
Selection.Copy
ActiveWindow.SelectedSheets.Visible = False
ThisWorkbook.Sheets("Stock History").Activate
Range("N1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.DisplayAlerts = False
On Error Resume Next
Workbooks("Gas Stock Take v2").Close SaveChanges:=True
On Error GoTo 0
Application.DisplayAlerts = True
ThisWorkbook.Sheets("Stock Take").Activate
Call Click
End Sub
Public Function GetLastRow(ByVal ws As Worksheet, Optional ByVal columnNumber As Long = 1)
As Long
With ws
GetLastRow = .Cells(.Rows.Count, columnNumber).End(xlUp).Row
End With
End Function
'''
Your error handling is fine. Using On Error GoTo 0 turns off On Error Resume Next.
I think the issue is the amount of data you're leaving on the clipboard after copy and paste. If you use .copy and .paste always follow that up with Application.CutCopyMode = False

Excel VBA .saveas premission denied with onedrive

I've created a macro to get data from active workbook, copy it into a new one and save new file. Whole code worked perfect until I changed Office to 365 with Onedrive on my computer.
When I run this macro, I get error 1004: Premission denied in macro below
Sub create_new()
Dim SheetI As Worksheet
Dim SheetO As Worksheet
Dim BookO As Workbook
Dim BookI As Workbook
Dim row As Long
Dim i As Long
Dim dict As Object
Dim path As String
Dim brng As Range
Dim found As Boolean
path = CreateObject("WScript.Shell").SpecialFolders("MyDocuments") & "\path\"
If Len(Dir(path, vbDirectory)) = 0 Then MkDir path
path = path & _
Format(Date, "ddmmmyyyy") & ".xlsx"
If Dir(path) <> "" Then Kill path
Set BookI = ThisWorkbook
Set BookO = Workbooks.Add
With BookO
BookO.Sheets.Add.Name = "Name"
Set SheetO = BookO.Sheets("Name")
SheetO.Cells(1, 1).Value = "1"
SheetO.Cells(1, 2).Value = "2"
SheetO.Cells(1, 3).Value = "3"
SheetO.Columns("A:H").AutoFit
SheetO.Range("a1:h1").Font.Bold = True
Application.DisplayAlerts = False
.SaveAs path
Application.DisplayAlerts = True
End With
Set dict = SubTotals(BookI)
For Each SheetI In BookI.Sheets
If SheetI.Name <> "Dane" Then
For row = 10 To SheetI.Cells(Rows.Count, 1).End(xlUp).row Step 1
If i <= row Then
If SheetI.Cells(row, 2).Value = "Oprysk" Then
If Not found Then found = True
i = row
If SheetI.Cells(row, 2).MergeCells Then i = row + SheetI.Cells(row, 2).MergeArea.Rows.Count - 1
With BookO
Range(SheetI.Cells(row, 1), SheetI.Cells(i, 1)).Copy
SheetO.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Range(SheetI.Cells(row, 5), SheetI.Cells(i, 8)).Copy
SheetO.Cells(Rows.Count, 5).End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
SheetI.Cells(2, 2).Copy
SheetO.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
SheetI.Cells(3, 5).Copy
SheetO.Cells(Rows.Count, 3).End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
SheetO.Cells(Rows.Count, 4).End(xlUp).Offset(1, 0).Value = SearchDict(dict, SheetO.Cells(Rows.Count, 3).End(xlUp).Value)
If i <> row Then
For l = 1 To 8 Step 1
If l <> 6 And l <> 7 Then
Application.DisplayAlerts = False
Range(SheetO.Cells(Rows.Count, l).End(xlUp), SheetO.Cells(Rows.Count, l).End(xlUp).Offset(i - row, 0)).Merge
Application.DisplayAlerts = True
End If
Next l
End If
End With
End If
End If
Next row
End If
Next SheetI
If found Then
Set brng = Range(SheetO.Cells(1, 1), SheetO.Cells(Rows.Count, 6).End(xlUp).Offset(0, 2))
With BookO
brng.BorderAround xlContinuous, xlThin
brng.Borders(xlInsideHorizontal).LineStyle = xlContinuous
brng.Borders(xlInsideVertical).LineStyle = xlContinuous
Application.DisplayAlerts = False
.SaveAs path
Application.DisplayAlerts = True
End With
MsgBox "File saved in path: " & path
Else
With BookO
Application.DisplayAlerts = False
BookO.Close
Application.DisplayAlerts = True
End With
Kill path
MsgBox "Data not found"
End If
End Sub
So basicly I check here if the path and file exists. If not, its created. I save the new workbook for the first time when its formated but before data is copied. Secondly its saved when the data is copied and this second attempt to save workbook fails with error above. Why I was able to overwrite this workbook when I didnt use Onedrive and now, when I do it shows me the error?

Copy and paste a row into column using macro

I am very new to the macro..
Basically I wanted to copy a row (E23 to H23) from worksheet named "Present month" of one workbook to a column of another worksheet named "ANA" (K4 to K7) in another workbook.
Please help me out!!
Edit1: Code from comment
Sub Copy_and_update_last_col_Census()
Range("K4:K7").Select
Selection.ClearContents
Application.WindowState = xlNormal
'the below line throws error
Windows("NOL_Support_Ticket_Status_Report").Activate
Range("E25:H25").Select
Selection.copy
Windows("Charts.xlsm").Activate
Range("K9").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Selection.copy
Range("K4").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
Application.CutCopyMode = False
Range("K9:N9").Select
Selection.ClearContents
End Sub
This is a tip. Go to the Developers tab -> Record Macro -> do the actions you want -> stop recording and woila press alt + F11 and check out the module.
F8 is your friend and you can see what your recorded macro does!!!
try this:
Sub Copy_and_update_last_col_Census()
Dim wb As Workbook
Dim rng2copy As Range, rng2paste As Range
Dim query As Integer
Dim myfile
Dim filename As String
'~~> I assumed that Charts.xlsm is the workbook you are running the macro
Set rng2paste = ThisWorkbook.Sheets("ANA").Range("K4")
filename = "NOL_Support_Ticket_Status_Report.xlsx"
'~~> Handles the error if workbook is not open
On Error Resume Next
Set wb = Workbooks(filename)
'~~> check for error and execute action necessary
If Err.Number <> 0 Then
query = MsgBox("Source workbook not open." & vbNewLine & _
"Do you want to open it?", vbYesNo)
Else
GoTo proceedcopy
End If
If query = 6 Then
myfile = Application.GetOpenFilename(Filefilter:="Excel Files (*.xlsx), *.xlsx")
Else
MsgBox "Exiting now."
Exit Sub
End If
'~~> check if user selected the correct file
If myfile <> False Then
If Dir(myfile) = filename Then
Set wb = Workbooks.Open(myfile)
Else
MsgBox "Wrong file loaded." & vbNewLine & _
"Exiting now."
Exit Sub
End If
Else
MsgBox "No file loaded." & vbNewLine & _
"Exiting now."
Exit Sub
End If
'~~> this do the actual copying
proceedcopy:
Set rng2copy = wb.Sheets("Present Month").Range("E23", "H23")
rng2copy.Copy
rng2paste.PasteSpecial xlPasteValues, , , True
Application.CutCopyMode = False
wb.Close False
End Sub
This is tried and tested.
But i can't say that i've structured it well enough.
So i leave further testing to you.

Worksheet Paste values/Save as then return the original file using vba

I have a workbook which performs several Excel-functions that depend on one variable and fills out itself. I have a loop to create those forms and save in a directory but before that I want to copy all and paste special so that formulas will be gone.
Sub SaveAs1()
For i = 172 To 225
Dim SaveName As Integer
SaveName = ActiveWorkbook.Sheets(1).Range("bi1").value
Application.ActiveWorkbook.SaveAs "C:\" & SaveName
Range("bi1") = i + 1
Next
End Sub
I figure that out finally using trial and error method
Sub Save()
Rem kaydetmece dongusu
For i = 172 To 180 Step 1
Application.DisplayAlerts = False
Workbooks.Open Filename:="C:\"
Range("bi1") = i + 1
Dim SaveName As Integer
SaveName = ActiveWorkbook.Sheets(1).Range("bi1").value
Range("A1:BE63").Select
Range("a1").Activate
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Application.ActiveWorkbook.SaveAs "C:\" & SaveName
Columns("BE:BU").Select
Selection.Delete Shift:=xlToLeft
Sheets("CAL").Select
ActiveWindow.SelectedSheets.Delete
Sheets("sahadan").Select
ActiveWindow.SelectedSheets.Delete
ActiveWorkbook.Close True
Next
End Sub
If you're asking how to paste values, this is how you do it. Replace "A1" with the actual range you need to use.
Range("A1").Copy
Range("A1").PasteSpecial xlPasteValues

Resources