Macro to save file if cells are filled - excel

I want to save my file in a particular SharePoint folder when I press a button.
Within the same Excel spreadsheet I have data validation cells that should not be blank. If they are blank the macro should give me an error message and tell me that certain cells are blank and needs to be filled. If they are not blank, then save the file in the SharePoint folder.
My macro is as follows:
Private Sub CommandButton1_Click()
Dim Path As String
Dim FileName1 As String
Path = "https://xxx.sharepoint.com/sites/xxxx/xxxxxxxxxxxxx/"
FileName1 = Range("$B$2").Text
ActiveWorkbook.SaveAs Filename:=Path & FileName1 & ".xlsx", _
FileFormat:=xlOpenXMLWorkbook
Application.DisplayAlerts = True
ActiveWorkbook.Close
End Sub
The cells are AD9:AM9 and AD10:AM10

This if statement checks if cells are empty and proceeds to end the macro before saving if the range is empty. I merged your ranges as they are adjacent.
Private Sub CommandButton1_Click()
Dim Path As String
Dim FileName1 As String
If WorksheetFunction.CountA(Range("AD9:AM10")) = 0 Then
MsgBox "Data Validation Fields are empty"
end ' stops the macro from running
Else
Path = "https://xxx.sharepoint.com/sites/xxxx/xxxxxxxxxxxxx/"
FileName1 = Range("$B$2").Text
ActiveWorkbook.SaveAs Filename:=Path & FileName1 & ".xlsx", _
FileFormat:=xlOpenXMLWorkbook
Application.DisplayAlerts = True
ActiveWorkbook.Close
End if
End Sub

Please use the Workbook_BeforeSave event like this:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim sh As Worksheet, rng As Range, emptRng As Range
Set sh = ActiveSheet 'use here your sheet
Set rng = sh.Range("AD9:AM10")
On Error Resume Next
Set emptRng = rng.SpecialCells(xlCellTypeBlanks)
If Err.Number = 0 Then
Cancel = True
MsgBox "There are empty cells in the range " & rng.Address & "." & vbCrLf & _
"Please check, correct and save again after that..."
End If
On Error GoTo 0
End Sub

Related

Deleted sheet using VBA appears again if we close the script and rerun it

I am trying to delete a sheet using macro and also the corresponding text containing the sheet name which was deleted is also to be deleted from the table in column BP simultaneously. Everything is working well. But when I close excel and open and run the script again. The sheet which was previously deleted again appears back. I am attaching the code as shown below
Kindly help. What could be the reason for this?
Private Sub CommandButton2_Click()
Dim xWs As Worksheet
Dim wb As Workbook
Dim sheetName As String
Dim z As Long
Dim last As Long
ThisWorkbook.Activate
sheetName = Application.InputBox("Please enter the OSAT Name:", "OSAT", _
, , , , , 2)
last = ThisWorkbook.Worksheets("DataStorage").Cells(Rows.Count, "BP").End(xlUp).Row
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Err.Clear
On Error Resume Next
Set xWs = Sheets(sheetName)
If Err <> 0 Then
MsgBox "The OSAT '" & sheetName & "'" & "does not exist!", vbInformation, "Excel 10 Tutorial"
Exit Sub
Else
xWs.Delete
MsgBox "The OSAT '" & sheetName & "'" & "has been deleted!", vbInformation, "Excel 10 Tutorial"
For z = last To 2 Step -1
If ThisWorkbook.Worksheets("DataStorage").Cells(z, "BP").Value = sheetName Then
Sheets("DataStorage").Cells(z, "BP").Delete
End If
Next z
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
The guidelines contained in the previous comments are very important and must be followed.
To temporarily test for a solution, try this, substituting xWs.Delete with these lines:
Dim oWB As Excel.Workbook
Set oWB = xWs.Parent
xWs.Delete
oWB.Save

Deleted sheet using VBA appears again if the script is used as add in

I am trying to delete a sheet using macro and also the corresponding text containing the sheet name which was deleted is also to be deleted from the table in column BP simultaneously. Everything is working well. But when the script is used as add in then The sheet which was previously deleted again appears back. I am attaching the code as shown below
Kindly help. What could be the reason for this?
Private Sub CommandButton2_Click()
Dim xWs As Worksheet
Dim wb As Workbook
Dim sheetName As String
Dim z As Long
Dim last As Long
ThisWorkbook.Activate
sheetName = Application.InputBox("Please enter the OSAT Name:", "OSAT", _
, , , , , 2)
last = ThisWorkbook.Worksheets("DataStorage").Cells(Rows.Count, "BP").End(xlUp).Row
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Err.Clear
On Error Resume Next
Set xWs = Sheets(sheetName)
If Err <> 0 Then
MsgBox "The OSAT '" & sheetName & "'" & "does not exist!", vbInformation, "Excel 10 Tutorial"
Exit Sub
Else
xWs.Delete
MsgBox "The OSAT '" & sheetName & "'" & "has been deleted!", vbInformation, "Excel 10 Tutorial"
For z = last To 2 Step -1
If ThisWorkbook.Worksheets("DataStorage").Cells(z, "BP").Value = sheetName Then
Sheets("DataStorage").Cells(z, "BP").Delete
End If
Next z
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
Thisworkbook references the Add-Ins file. If you close Excel the add-in won't get saved. Therefore the deletion is reset.
You need to add this to the Thisworkbook module
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Thisworkbook.save
End Sub
BUT: are you sure you want to save data in an Add-In?

Spreadsheet not found in the workbook, even if that spreadsheet exists

I have this small piece of code:
NombreLibro = Application.GetOpenFilename()
Set Libro = Workbooks.Open(NombreLibro, , False)
If Val(Application.Version) > 15 Then 'I tried this but it doesn't solve the problem
Libro.AutoSaveOn = False
End If
With Libro
For i = 1 To .Worksheets.Count
If .Worksheets(i).CodeName = "Sheet1" Then 'HERE I HAVE THE PROBLEM
(doing something)
End If
Next i
End With
Sometimes the "if" is false even if the workbook actually has the "Sheet1".
But if I run this again, adding a stop in the code to check what is going on, then the piece of code works as expected.
I am downloading the workbooks from a company website and run the code right away.
I have OneDrive in my computer. So I am wondering if OneDrive is busy uploading the file and then Excel doesn't access it correctly?
What do you suggest I could try?
EDIT:
Following VBasic2008 suggestion (see his/her answer) I changed a little the code, but it kept failing. I then added a debug MsgBox:
For Each ws In Libro.Worksheets
MsgBox "CodeName: " & ws.CodeName & vbLf _
& "Name: " & ws.Name & vbLf & "Libro: " & Libro.Name 'I added this
If ws.CodeName = wsCodeName Then
wasFound = True
Exit For ' The worksheet is found, no need to loop anymore.
End If
Next ws
Result (shown in the MsgBox):
CodeName: 'blank!!!
Name: SheetName 'correct
Libro: LibroName 'correct
Is there a bug in Excel related to CodeNames?
EDIT2: (WORKAROUND)
I download the files from a company website, the data on the website is on a table and then a converter downloads it into Excel format.
I think the downloaded file is not quite Excel format and the CodeName is not filled. When Excel opens it and then the VBA editor is opened, Excel fills out the CodeName with a standard name.
In my case, as the fresh downloaded files have only one sheet, I can use this workaround:
For Each ws In Libro.Worksheets
If ws.CodeName = wsCodeName Or ws.CodeName = "" Then
wasFound = True
Exit For
End If
Next ws
This will work the first time the file is processed ws.CodeName = "" and the next times ws.CodeName = wsCodename
Using Worksheet CodeName
Option Explicit
Sub testCodeName()
Const wsCodeName As String = "Sheet1"
' Choose file (workbook, spreadsheet).
Dim NombreLibro As Variant
NombreLibro = Application.GetOpenFilename()
' Validate workbook.
If NombreLibro = False Then
MsgBox "You canceled.", vbExclamation, "Canceled"
Exit Sub
End If
' Open and create a reference to the workbook.
Dim Libro As Workbook: Set Libro = Workbooks.Open(NombreLibro, , False)
' Attempt to find the worksheet.
Dim ws As Worksheet
Dim wasFound As Boolean
For Each ws In Libro.Worksheets
If ws.CodeName = wsCodeName Then
wasFound = True
Exit For ' The worksheet is found, no need to loop anymore.
End If
Next ws
' Validate worksheet.
If Not wasFound Then
MsgBox "Worksheet not found.", vbExclamation, "Not Found"
Exit Sub
End With
' Continue with the code
With ws
' e.g. see if it's true.
MsgBox "Worksheet found:" & vbLf _
& "Name: " & .Name _
& vbLf & "CodeName: " & .CodeName, vbInformation, "Success"
End With
End Sub
I'm somewhat of a VBA noob but I wrote this simple code a while back to search for a worksheet and delete it:
Dim sht As Worksheet
For Each sht In ThisWorkbook.Worksheets
If Application.Proper(sht.Name) = Application.Proper("Company Data") Then
Sheets("Company Data").Select
Application.DisplayAlerts = False
ActiveWindow.SelectedSheets.Delete
Application.DisplayAlerts = True
End If
Next sht
Maybe this can help?

VBA Saving only Visible Data into New Sheet in the same Path

I'm relatively new to VBA. I worked on the following code, which workED perfectly until I decided to filter for non-blanks before saving the sheet.
The idea is to save my sheet in the same path after filtering out any blank values. The new file will be values only in CSV. Again, all of that worked, except when it comes to filtering the data and saving the file.
Now I get the
"Run-time error 438 Object doesn’t support this property or method"
on the code below
ThisWorkbook.Sheets("SHEET1").SpecialCells(xlCellTypeVisible).Copy
The full code
Private Sub CommandButton1_Click()
If Sheets("SHEET1").AutoFilterMode Then Sheets("SHEET1").AutoFilterMode = False
sDate = Format(Sheets("SHEET2").Range("F1"), "YYYY.MM.DD")
cell = "NAME - " & sDate
ThisWorkbook.Sheets("SHEET1").Range("A:C").AutoFilter Field:=2, Criteria1:="<>"
ThisWorkbook.Sheets("SHEET1").SpecialCells(xlCellTypeVisible).Copy
With ActiveSheet.UsedRange
.Value = .Value
End With
ActiveWorkbook.SaveAs ThisWorkbook.Path & "\" & cell & ".csv", FileFormat:=xlCSV
End Sub
Please read the code's comments and adjust it to fit your needs
EDIT: Adjusted a type in this row sourceSheet.UsedRange.SpecialCells(xlCellTypeVisible).Copy targetWorkbook.Worksheets(targetWorkbook.Sheets.Count).Range("A1")
Private Sub CommandButton1_Click()
Dim targetWorkbook As Workbook
Dim sourceSheet As Worksheet
Dim formatDate As String
Dim fileName As String
Set sourceSheet = ThisWorkbook.Worksheets("Sheet1")
' Remove filter
If sourceSheet.AutoFilterMode Then sourceSheet.AutoFilterMode = False
If sourceSheet.Range("F1").Value <> vbNullString Then
formatDate = Format(sourceSheet.Range("F1").Value, "YYYY.MM.DD")
End If
' Set the new workbook file name
fileName = "NAME - " & formatDate
' Filter the fileNames
sourceSheet.Range("A:C").AutoFilter Field:=2, Criteria1:="<>"
' Add new workbook and set reference
Set targetWorkbook = Workbooks.Add
' Copy the visible fileNames in a new workbook
sourceSheet.UsedRange.SpecialCells(xlCellTypeVisible).Copy targetWorkbook.Worksheets(targetWorkbook.Sheets.Count).Range("A1")
' Save the new workbook
targetWorkbook.SaveAs ThisWorkbook.Path & "\" & fileName & ".csv", FileFormat:=xlCSV
End Sub
Let me know if it works

VBA Naming the New Workbook using a Phrase, Cell Reference, and Date from a Cell

I have the following code that produces a new worksheet. I'm trying to name the new worksheet using a Phrase, the content in Cell 1, and the date in Cell 2.
Cell 1 will contain some data that are inserted via Data Validation (4 options in total) and Cell 2 will have a date.
EXAMPLE:
Worksheet INPUTS Range C3. Cell 1 value = Trade Activities, Purchases, Sales...etc
Worksheet INPUTS Range C2. Cell 2 value = 2.11.2020
The new workbook's name will be "Client Name Trade Activities - 2.11.2020"
both Cell 1 and Cell 2 will be in the INPUTS worksheet
Private Sub CommandButton1_Click()
Dim targetWorkbook As Workbook
Dim sourceSheet As Worksheet
Dim formatDate As String
Dim fileName As String
Set sourceSheet = ThisWorkbook.Worksheets("Sheet1")
If sourceSheet.AutoFilterMode Then sourceSheet.AutoFilterMode = False
If ThisWorkbook.Worksheets("INPUTS").Range("C3").Value <> vbNullString Then
formatDate = Format(Sheets("INPUTS").Range("C3"), "YYYY.MM.DD")
End If
fileName = "Name - " & ActivityName & formatDate
sourceSheet.Outline.ShowLevels ColumnLevels:=1
sourceSheet.Range("A:M").AutoFilter Field:=12, Criteria1:="<>0"
Set targetWorkbook = Workbooks.Add
sourceSheet.UsedRange.SpecialCells(xlCellTypeVisible).Copy targetWorkbook.Worksheets(targetWorkbook.Sheets.Count).Range("A1")
targetWorkbook.Sheets("sheet1").Columns("A:AC").EntireColumn.AutoFit
targetWorkbook.SaveAs ThisWorkbook.Path & "\" & fileName & ".xlsx", FileFormat:=51
End Sub
Some things to remember:
Define and reuse your variables whenever you can
Try to add comments to your code, explaining the purpose of what you're doing (your future self or whom ever is going to work with your files, is going to thank you)
Leave spaces between your code's main parts, so it's more readable
EDIT: Added error handler, for when user clicks "No" when asking to overwrite existing file
Code:
Private Sub CommandButton1_Click()
Dim targetWorkbook As Workbook
Dim sourceSheet As Worksheet
Dim formatDate As String
Dim fileName As String
On Error GoTo CleanFail
Set sourceSheet = ThisWorkbook.Worksheets("Sheet1")
' Remove filter
If sourceSheet.AutoFilterMode Then sourceSheet.AutoFilterMode = False
If sourceSheet.Range("F1").Value <> vbNullString Then
formatDate = Format(sourceSheet.Range("F1").Value, "YYYY.MM.DD")
End If
' Set the new workbook file name
fileName = "NAME - " & formatDate
' Filter the fileNames
sourceSheet.Range("A:C").AutoFilter Field:=2, Criteria1:="<>"
' Add new workbook and set reference
Set targetWorkbook = Workbooks.Add
' Copy the visible fileNames in a new workbook
sourceSheet.UsedRange.SpecialCells(xlCellTypeVisible).Copy targetWorkbook.Worksheets(targetWorkbook.Sheets.Count).Range("A1")
' Save the new workbook
targetWorkbook.SaveAs ThisWorkbook.Path & "\" & fileName & ".csv", FileFormat:=xlCSV
CleanExit:
Exit Sub
CleanFail:
Select Case Err.Number
Case 1004
MsgBox "You cancel the process"
Resume Next
Case Else
' Do something else? handle it properly...
MsgBox "Something went wrong..."
Resume CleanExit
End Select
End Sub
Let me know if it works

Resources