Save 2 different worksheets in the same workbook using coding - vba

I use Excel to do an invoice system for my company. I've had to make it "dummy proof" for some of the other employees that use the program. I use several codes to make it successful. I have two sheets: Carolina Fireworks Order Form and Back Order. There is a macro on Carolina Fireworks Order Form that copies any cells over to the Back Order Form (this is an exact copy of Carolina Fireworks Order Form except that in the C7 where customer name is placed it automatically says Customer name and BO).
I have a code that automatically saves the file into a specific folder with C7 (customer name) and current date. Is there a way that I can add a code that if I hit the macro button to copy over the BO cells that it will automatically save Back Order sheet seperately with file name C7 and current date? Then when I hit the x buttom my other code will automatically save Carolina Fireworks Order Form (sheet 1)?
Does this make sense? I'm not a code writer so I had to search forever to get the code below to work. If there is a better way to do this then I'm completely open to it! Below is the current code that I am using for Module 1:
Sub myOpenCode()
'Standard module code, like: Module1.
Dim strCustomer$, strMsg$, myUpDate$, strCustNm$
Application.EnableEvents = True
On Error GoTo myErr
strCustomer = Sheets("Carolina Fireworks Order Form").Range("C7").Value
'Test for current customer!
If strCustomer <> "" Then
strMsg = "The current customer name is:" & vbLf & vbLf & _
strCustomer & vbLf & vbLf & _
"Change this customer name to a different Name?"
'Test for customer name update?
myUpDate = MsgBox(strMsg, vbQuestion + vbYesNo, "Add Customer?")
'Chose "Yes" button!
If myUpDate = 6 Then
'Change current customer's name!
strCustNm = InputBox(strMsg, "Change Customer Name!", "")
End If
'Chose "No" button!
If myUpDate = 7 Then
'Keep current customer name!
Application.EnableEvents = True
Exit Sub
End If
Else
'Get customer name!
strMsg = "The current customer name is:" & vbLf & vbLf & _
"""EMPTY!""" & vbLf & vbLf & _
"Add a customer name:"
'Force add customer name add!
myGetCustNm:
strCustNm = InputBox(strMsg, "Add Customer Name!", "")
If strCustNm = "" Then GoTo myGetCustNm
End If
'Load customer name!
Sheets("Carolina Fireworks Order Form").Range("C7").Value = strCustNm
Application.EnableEvents = True
Exit Sub
myErr:
'GoTo Error routine!
Call myErrHandler(Err)
End Sub
Sub myCloseCode()
'Standard module code, like: Module1.
Dim strDate$, strCustomer$, strFileNm$, strMsg$, myUpDate$
Application.EnableEvents = False
On Error GoTo myErr
'Test for Save option or Exit without saving?
strMsg = "Save this file before closing?"
myUpDate = MsgBox(strMsg, vbQuestion + vbYesNo, "Save Now?")
'Chose "Yes" button!
If myUpDate = 6 Then GoTo mySave
'Chose "No" button!
If myUpDate = 7 Then
Application.EnableEvents = True
Exit Sub
End If
mySave:
'Build file name!
strDate = DatePart("m", Date) & "-" & _
DatePart("d", Date) & "-" & _
Right(DatePart("yyyy", Date, vbUseSystemDayOfWeek, vbUseSystem), 4)
strCustomer = Sheets("Carolina Fireworks Order Form").Range("C7").Value
strFileNm = "\\Owner-hp\Users\Public\Customers\" & strCustomer & "-" & strDate & ".xlsm"
'Save current file!
ActiveWorkbook.SaveAs Filename:=strFileNm
Application.EnableEvents = True
ActiveWorkbook.Close
Exit Sub
myErr:
'GoTo Error routine!
Call myErrHandler(Err)
Application.EnableEvents = True
End Sub
Private Sub myErrHandler(myErr As ErrObject)
'Standard module code, like: Module1.
'Error Trap Routine!
Dim myMsg$
'Build Error Message!
myMsg = "Error Number : " & Str(myErr.Number) & vbLf & _
"Error Location: " & myErr.Source & vbLf & _
"Error Description: " & myErr.Description & vbLf & vbLf & _
"Context: " & myErr.HelpContext & vbLf & _
"Help File: " & myErr.HelpFile
'Show Error Message!
MsgBox myMsg & vbLf & vbLf & _
"Use the ""Help"" button for more information, on this ERROR!", _
vbCritical + vbMsgBoxHelpButton, _
Space(3) & "Error!", _
myErr.HelpFile, _
myErr.HelpContext
End Sub
Module 2:
Sub CopyBO()
'Copy cells of cols A,B,D from rows containing "BO" in
'col I of the active worksheet (source sheet) to cols
'A,B,D of Sheet2 (destination sheet)
Dim DestSheet As Worksheet
Set DestSheet = Worksheets("Back Order")
Dim sRow As Long 'row index on source worksheet
Dim dRow As Long 'row index on destination worksheet
Dim sCount As Long
sCount = 0
For sRow = 1 To 65536
'use pattern matching to find "BO" anywhere in cell
If Cells(sRow, "I") Like "*BO*" Then
sCount = sCount + 1
'copy cols A,B, D
Cells(sRow, "A").Copy Destination:=DestSheet.Cells(sRow, "A")
Cells(sRow, "B").Copy Destination:=DestSheet.Cells(sRow, "B")
End If
Next sRow
MsgBox sCount & " Back Ordered rows copied", vbInformation, "Transfer Done"
End Sub

Below code will create a copy of Back Order Sheet when procedure CopyBO is called.
Sub CopyBO()
'Copy cells of cols A,B,D from rows containing "BO" in
'col I of the active worksheet (source sheet) to cols
'A,B,D of Sheet2 (destination sheet)
Dim DestSheet As Worksheet
Set DestSheet = Worksheets("Back Order")
Dim n_Wkb As Workbook ' new workbook
Dim strFileNm As String
Dim sRow As Long 'row index on source worksheet
Dim dRow As Long 'row index on destination worksheet
Dim sCount As Long
sCount = 0
For sRow = 1 To 65536
'use pattern matching to find "BO" anywhere in cell
If Cells(sRow, "I") Like "*BO*" Then
sCount = sCount + 1
'copy cols A,B, D
Cells(sRow, "A").Copy Destination:=DestSheet.Cells(sRow, "A")
Cells(sRow, "B").Copy Destination:=DestSheet.Cells(sRow, "B")
End If
Next sRow
If sCount > 0 Then
DestSheet.Copy
Set n_Wkb = ActiveWorkbook
' Get the file path
strCustomer = ThisWorkbook.Sheets("Carolina Fireworks Order Form").Range("C7").Value
strFileNm = "\\Owner-hp\Users\Public\Customers\" & strCustomer
strFileNm = strFileNm & Format(Now(), "DD-MM-YY hh.mm.ss") & ".xlsx"
'save
n_Wkb.SaveAs strFileNm
n_Wkb.Close
End If
MsgBox sCount & " Back Ordered rows copied", vbInformation, "Transfer Done"
End Sub

Related

Check which worksheets to export as pdf

I am a beginner in Excel VBA but I would like to create a file where I can select certain worksheets by means of a userform with checkboxes. In principle, it is then intended that only the check boxes where the value is true should be exported.
Below I have 2 codes that work well separately from each other but I have not yet been able to get them to work together.
Note: both codes come from the internet.
If possible I would like to write a loop to keep the overview.
the code to export sheets as pdf and put them in a outlook
Sub Saveaspdfandsend1()
Dim xSht As Worksheet
Dim xFileDlg As FileDialog
Dim xFolder As String
Dim xYesorNo, I, xNum As Integer
Dim xOutlookObj As Object
Dim xEmailObj As Object
Dim xUsedRng As Range
Dim xArrShetts As Variant
Dim xPDFNameAddress As String
Dim xStr As String
xArrShetts = Array("test", "Sheet1", "Sheet2") 'Enter the sheet names you will send as pdf files enclosed with quotation marks and separate them with comma. Make sure there is no special characters such as \/:"*<>| in the file name.
For I = 0 To UBound(xArrShetts)
On Error Resume Next
Set xSht = Application.ActiveWorkbook.Worksheets(xArrShetts(I))
If xSht.Name <> xArrShetts(I) Then
MsgBox "Worksheet no found, exit operation:" & vbCrLf & vbCrLf & xArrShetts(I), vbInformation, "Kutools for Excel"
Exit Sub
End If
Next
Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
If xFileDlg.Show = True Then
xFolder = xFileDlg.SelectedItems(1)
Else
MsgBox "You must specify a folder to save the PDF into." & vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Must Specify Destination Folder"
Exit Sub
End If
'Check if file already exist
xYesorNo = MsgBox("If same name files exist in the destination folder, number suffix will be added to the file name automatically to distinguish the duplicates" & vbCrLf & vbCrLf & "Click Yes to continue, click No to cancel", _
vbYesNo + vbQuestion, "File Exists")
If xYesorNo <> vbYes Then Exit Sub
For I = 0 To UBound(xArrShetts)
Set xSht = Application.ActiveWorkbook.Worksheets(xArrShetts(I))
xStr = xFolder & "\" & xSht.Name & ".pdf"
xNum = 1
While Not (Dir(xStr, vbDirectory) = vbNullString)
xStr = xFolder & "\" & xSht.Name & "_" & xNum & ".pdf"
xNum = xNum + 1
Wend
Set xUsedRng = xSht.UsedRange
If Application.WorksheetFunction.CountA(xUsedRng.Cells) <> 0 Then
xSht.ExportAsFixedFormat Type:=xlTypePDF, Filename:=xStr, Quality:=xlQualityStandard
Else
End If
xArrShetts(I) = xStr
Next
'Create Outlook email
Set xOutlookObj = CreateObject("Outlook.Application")
Set xEmailObj = xOutlookObj.CreateItem(0)
With xEmailObj
.Display
.To = ""
.CC = ""
.Subject = "????"
For I = 0 To UBound(xArrShetts)
.Attachments.Add xArrShetts(I)
Next
If DisplayEmail = False Then
'.Send
End If
End With
End Sub
the other code i tried I can see which checkbox is checked unfortunately I can't rewrite it so only the checked boxes will be exported to pdf.
Private Sub CommandButton100_Click()
For i = 100 To 113
If UserForm2.Controls("CheckBox" & i).Value = True Then
a = a + 1
End If
Next i
k = 1
For i = 100 To 113
If UserForm2.Controls("CheckBox" & i).Value = True And a = 1 Then
b = UserForm2.Controls("CheckBox" & i).Caption & "."
ElseIf UserForm2.Controls("CheckBox" & i).Value = True And k <> a Then
b = b & UserForm2.Controls("CheckBox" & i).Caption & ", "
k = k + 1
ElseIf UserForm2.Controls("CheckBox" & i).Value = True And k = a Then
b = b & "and " & UserForm2.Controls("CheckBox" & i).Caption & "."
End If
Next i
MsgBox ("You have selected " & b)
End Sub
Can someone help me please I am struggling for some time now?
Please, try the next function:
Private Function sheetsArr(uF As UserForm) As Variant
Dim c As MSForms.Control, strCBX As String, arrSh
For Each c In uF.Controls
If TypeOf c Is MSForms.CheckBox Then
If c.value = True Then strCBX = strCBX & "," & c.Caption
End If
Next
sheetsArr = Split(Mid(strCBX, 2), ",") 'Mid(strCBX, 2) eliminates the first string character (",")
End Function
It will return an array composed from the ticked check boxes caption.
It can be used demonstratively, in this way:
Sub testSheetsArrFunction()
Debug.Print Join(sheetsArr(UserForm2), ",")
End Sub
The above code will return in Immediate Window a string containing the checked check boxes caption (separated by comma). It may be run from a standard module, too. Of course, the function must be copied in that module. And the form to be loaded, having some check boxes ticked.
Now, you have to change a single code line in your (working) code:
Replace:
xArrShetts = Array("test", "Sheet1", "Sheet2")
with:
xArrShetts = sheetsArr(UserForm2)
It should use the array built in the above function. Of course the function have to be copied in the module where to be called. If placed in the form code module, it can be simple called as:
xArrShetts = sheetsArr(Me)
Edited:
You should only paste the next code in the form code module and show the form:
Private Sub CommandButton1_Click()
Dim xSht As Worksheet
Dim xFileDlg As FileDialog
Dim xFolder As String
Dim xYesorNo, I, xNum As Integer
Dim xOutlookObj As Object
Dim xEmailObj As Object
Dim xUsedRng As Range
Dim xArrShetts As Variant
Dim xPDFNameAddress As String
Dim xStr As String
'xArrShetts = Array("test", "Sheet1", "Sheet2") 'Enter the sheet names you will send as pdf files enclosed with quotation marks and separate them with comma. Make sure there is no special characters such as \/:"*<>| in the file name.
xArrShetts = sheetsArr(Me)
For I = 0 To UBound(xArrShetts)
On Error Resume Next
Set xSht = Application.ActiveWorkbook.Worksheets(xArrShetts(I))
If xSht.Name <> xArrShetts(I) Then
MsgBox "Worksheet no found, exit operation:" & vbCrLf & vbCrLf & xArrShetts(I), vbInformation, "Kutools for Excel"
Exit Sub
End If
Next
Set xFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
If xFileDlg.Show = True Then
xFolder = xFileDlg.SelectedItems(1)
Else
MsgBox "You must specify a folder to save the PDF into." & vbCrLf & vbCrLf & "Press OK to exit this macro.", vbCritical, "Must Specify Destination Folder"
Exit Sub
End If
'Check if file already exist
xYesorNo = MsgBox("If same name files exist in the destination folder, number suffix will be added to the file name automatically to distinguish the duplicates" & vbCrLf & vbCrLf & "Click Yes to continue, click No to cancel", _
vbYesNo + vbQuestion, "File Exists")
If xYesorNo <> vbYes Then Exit Sub
For I = 0 To UBound(xArrShetts)
Set xSht = Application.ActiveWorkbook.Worksheets(xArrShetts(I))
xStr = xFolder & "\" & xSht.Name & ".pdf"
xNum = 1
While Not (Dir(xStr, vbDirectory) = vbNullString)
xStr = xFolder & "\" & xSht.Name & "_" & xNum & ".pdf"
xNum = xNum + 1
Wend
Set xUsedRng = xSht.UsedRange
If Application.WorksheetFunction.CountA(xUsedRng.Cells) <> 0 Then
xSht.ExportAsFixedFormat Type:=xlTypePDF, Filename:=xStr, Quality:=xlQualityStandard
End If
xArrShetts(I) = xStr
Next
'Create Outlook email
Set xOutlookObj = CreateObject("Outlook.Application")
Set xEmailObj = xOutlookObj.CreateItem(0)
With xEmailObj
.Display
.To = ""
.CC = ""
.Subject = "????"
For I = 0 To UBound(xArrShetts)
.Attachments.Add xArrShetts(I)
Next
If DisplayEmail = False Then
'.Send
End If
End With
End Sub
Private Function sheetsArr(uF As UserForm) As Variant
Dim c As MSForms.Control, strCBX As String, arrSh
For Each c In uF.Controls
If TypeOf c Is MSForms.CheckBox Then
If c.Value = True Then strCBX = strCBX & "," & c.Caption
End If
Next
sheetsArr = Split(Mid(strCBX, 2), ",") 'Mid(strCBX, 2) eliminates the first string character (",")
End Function

On Error Go To in a Loop

I am trying to create a loop that will look through a list of customers, and if there is a report for that customer, email that customer the report.
What I need is an On Error statement that will allow customers without reports to be skipped and allow the script to continue onto the next customer right up until the end of the customer list.
The On Error statement I have currently, gets stuck after all customers have been cycled through, and continues looping in the On Error statement.
Any help would be greatly appreciated!!!
sub test()
a = 2
Check:
Do Until UniqueBuyer.Range("A" & a).Value = ""
On Error GoTo ErrHandler:
Sheets(UniqueBuyer.Range("A" & a).Value).Activate
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
FolderLocation & FolderName & "\" & _
UniqueBuyer.Range("A" & a).Value & ".pdf" _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=Flase, OpenAfterPublish:=False
PDFFile = FolderLocation & FolderName & "\" & _
UniqueBuyer.Range("A" & a).Value & ".pdf"
Set OutLookApp = CreateObject("Outlook.Application")
Set OutlookMail = OutLookApp.createItem(0)
CombinedEmail = ""
'Clear variable - LK
On Error Resume Next
'Display email and specify To, Subject, etc
With OutlookMail
.Display
c = 4
Do Until UniqueBuyer.Cells(a, c).Value = ""
AdditionalEmail = UniqueBuyer.Cells(a, c)
CombinedEmail = CombinedEmail & ";" & AdditionalEmail
.to = CombinedEmail
c = c + 1
Loop
.cc = ""
.BCC = ""
.Subject = "Weekly Wooltrade Summary " & Left(Master.Range("X2"), 3)
.Body = ""
.Attachments.Add PDFFile
'.Send
End With
On Error GoTo 0
a = a + 1
Loop
Exit Sub
ErrHandler:
a = a + 1
GoTo Check
End Sub
the On Error GoTo way is hardly the one to go: you'd better check for any possible error and handle it
furthermore you'd also better instantiate one Outlook Application only for all needed emails
finally there were some typos (Flase -> False)
here's a possible (commented) refactoring of your code for what above:
Option Explicit
Sub test()
Dim UniqueBuyer As Worksheet, Master As Worksheet
Dim FolderLocation As String, FolderName As String, PDFFile As String
Dim OutLookApp As Object
Dim cell As Range
FolderLocation = "C:\Users\...\" '<--| change it to your actual folder location
FolderName = "Test" '<--| change it to your actual folder name
Set UniqueBuyer = Worksheets("UniqueBuyer") '<--| change "UniqueBuyer" to your actual Unique Buyer sheet name
Set Master = Worksheets("Master") '<--| change "Master" to your actual Master sheet name
Set OutLookApp = CreateObject("Outlook.Application") '<--| set one Outlook application outside the loop
With UniqueBuyer '<--| reference your "Unique Buyer" sheet
For Each cell In .Range("A2", .Cells(.Rows.Count, 1).End(xlUp)).SpecialCells(xlCellTypeConstants, xlTextValues) '<--| loop through its column A cells with constant (i.e. not from formulas) text content from row 2 down to last not empty one
PDFFile = FolderLocation & FolderName & "\" & cell.Value & ".pdf" '<--| build your PDF file name
With .Range(cell.Offset(, 3), cell.Offset(, 3).End(xlToRight)) '<--| reference current buyer cells from column 4 rightwards
If WorksheetFunction.CountA(.Cells) > 0 Then '<--| if any not-blank cells in referenced ones
If OKSheetAndExportToPDF(cell.Value, PDFFile) Then '<--| if successfully found current buyer sheet and exported it to PDF
'Display email and specify To, Subject, etc
With OutLookApp.createItem(0) '<--| create a new mail item and reference it
.Display
.to = GetCombinedEmails(.SpecialCells(xlCellTypeConstants, xlTextValues)) '<--| get emails string from currently referenced cells with some constant text value
.cc = ""
.BCC = ""
.Subject = "Weekly Wooltrade Summary " & Left(Master.Range("X2"), 3)
.Body = ""
.Attachments.Add PDFFile
'.Send
End With
End If
End If
End With
Next
End With
Set OutLookApp = Nothing
End Sub
Function GetCombinedEmails(rng As Range) As String
Dim cell As Range
With rng
If .Count = 1 Then
GetCombinedEmails = .Value
Else
GetCombinedEmails = Join(Application.Transpose(Application.Transpose(.Value)), ";") '<--| join all found consecutive email addresses in one string
End If
End With
End Function
Function OKSheetAndExportToPDF(shtName As String, PDFFile As String) As Boolean
On Error GoTo ExitFunction
With Worksheets(shtName)
.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=PDFFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
OKSheetAndExportToPDF = True
End With
ExitFunction:
End Function

Search worksheet for three names

Instead of looking for a number greater than 6 and sending it to another sheet. I want to look up 3 names so I can search a contact list and have it pull their information from the sheet to the report sheet.
below is my old code:
Private Sub CommandButton1_Click()
Dim ws As Worksheet, myCounter
Dim erow, myValue As Long
For Each ws In Sheets
If ws.Range("C3").Value > 6 Then
myCounter = 1
ws.Select
ws.Range("c3").Select
myValue = ws.Range("C3").Value
Worksheets("Report").Select
erow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Cells(erow, 1) = myValue
nextValue = MsgBox("Value found in " & ws.Name & Chr(10) & "Continue?", vbInformation + vbYesvbNo, ws.Name & " C3 = " & ws.Range("C3").Value)
Select Case nextValue
Case Is = vbYes
Case Is = vbNo
Exit Sub
End Select
End If
Next ws
If myCounter = 0 Then
MsgBox "None of the sheets contains a " & Chr(10) & "value greater than 6 in cell C3 ", vbInformation, "Not Found"
End If
End Sub
I think the third row should be String instead of Long.
The names I'm looking for are "David" "Andrea" & "Caroline", not sure if I write it three times or use a loop. Also I can't figure out how to search in the entire spreadsheet for these names.
The code below will look for the names "David", "Andrea" and "Caroline" in cell "C3" in all of the worksheets. For every match it will copy it to the first empty row in Column A in "Report" worksheet.
Note: There is no need to use Select and ActiveSheet, instead use fully qualifed Cells and Worksheets.
Code
Option Explicit
Private Sub CommandButton1_Click()
Dim ws As Worksheet, myCounter As Long
Dim erow As Long, myValue As Long
Dim nextValue As Long
For Each ws In ThisWorkbook.Sheets
With ws
Select Case .Range("C3").Value
Case "David", "Andrea", "Caroline"
myCounter = 1 ' raise flag >> found in at least 1 sheet
' get first empty row in "Report" sheet
erow = Worksheets("Report").Cells(Worksheets("Report").Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Worksheets("Report").Cells(erow, 1) = .Range("C3").Value
nextValue = MsgBox("Value found in " & .Name & Chr(10) & "Continue?", vbInformation + vbYesNo, .Name & " C3 = " & .Range("C3").Value)
Select Case nextValue
Case Is = vbYes ' <-- if you are not doing anything here, you don't need it >> maybe you don't need the entire `Select Case` here
Case Is = vbNo
Exit Sub
End Select
End Select ' Select Case .Range("C3").Value
End With
Next ws
If myCounter = 0 Then
MsgBox "None of the sheets contains the names " & Chr(10) & " 'David', 'Andrea', 'Caroline' in cell C3 ", vbInformation, "Not Found"
End If
End Sub
Comment: It seems you are not doing anything in the case of Case Is = vbYes in the Select Case below:
nextValue = MsgBox("Value found in " & .Name & Chr(10) & "Continue?", vbInformation + vbYesNo, .Name & " C3 = " & .Range("C3").Value)
Select Case nextValue
Case Is = vbYes ' <-- if you are not doing anything here, you don't need it >> maybe you don't need the entire `Select Case` here
Case Is = vbNo
Exit Sub
End Select
You can replace the entire thing with :
If MsgBox("Value found in " & .Name & Chr(10) & "Continue?", vbInformation + vbYesNo, .Name & " C3 = " & .Range("C3").Value) = vbNo Then
Exit Sub
End If

Search on all opened workbooks for specific data and select that one workbook to use his data

Sub SearchOnWorksheets()
Dim sPrompt As String
Dim msgTrap As VbMsgBoxResult
Dim xWBName As String
Dim xWBAbiertos As String
Dim wSheet As Worksheet
Dim wBook As Workbook
Dim rFound As Range
Dim bFound As Boolean
If Workbooks.Count >= 2 Then
For Each wBook In Application.Workbooks
xWBAbiertos = xWBAbiertos & "[ " & wBook.Name & " ]" & vbCrLf
Next
For Each wBook In Application.Workbooks
For Each wSheet In wBook.Worksheets
Set rFound = Nothing
Set rFound = wSheet.Cells.Find(What:="raya", After:=wSheet.Cells(1, 1), _
LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False)
If Not rFound Is Nothing Then
bFound = True
xWBName = wBook.Name & vbCrLf
Exit For
End If
Next wSheet
If bFound = True Then Exit For
Next wBook
sPrompt = "Archivos Excel abiertos:" & vbNewLine & _
vbNewLine & xWBAbiertos & vbNewLine & _
vbNewLine & "El archivo de donde se extraerán los gastos es:" & vbNewLine & _
vbNewLine & xWBName & vbNewLine & _
vbNewLine & ""
msgTrap = MsgBox(sPrompt, vbYesNo + vbExclamation, "CUBIMSA")
Select Case msgTrap
Case vbYes
Exit Sub
Case vbNo
Exit Sub
End Select
Else
Call MsgBox("THERE IS NO OPENED ARCHIVE." & vbNewLine & _
vbNewLine & "OPEN ARCHIVE", vbCritical, "ERROR")
Exit Sub
End If
End Sub
In this message appears the file "gastos.xls" because the code looks for the word "raya" in every opened workbook, but I need it to show all the workbooks that met this criteria.
Or maybe if it is possible in all the workbooks look for the sheet "Raya Semanal".
And I need to use this workbook to extract some information, how can I convert this string on something I can copy and paste in other workbook?
something like Workbooks("gastos.xls").Sheets("Raya Semanal").Range("Z16").Value
I think you are asking for 2 things:
I need it to show all the workbooks that met this criteria
In order to record all foundings for all the WBs you would need to change this line xWBName = wBook.Name & vbCrLf to xWBName = wBook.Name & vbCrLf & xWBName
And I need to use this workbook to extract some information, how can I convert this string on something I can copy and paste in other workbook?
I would use the split Function
Like so:
Dim ItemArray as Variant
For Each ItemArray in Split(xWBName ,vbCrlf) 'I may be wrong and probably you should use Chr(10) instead of vbcrlf
Workbooks(Cstr(ItemArray)).Sheets("Raya Semanal").Range("Z16").Value
Next ItemArray

Excel VBA - Log changes when old value of a cell is changed manually in Excel

I want to add detailed log with changes to the sheet "Audit" when a cell value is changed in Sheet 1. However no changes should be logged when value is entered in a blank cell. I am working on the below code , but unable to remove blank cell change logs.
Option Explicit
Const LiveWS As String = "Sheet1"
Const AuditWS As String = "Audit"
Private Sub Workbook_Open()
Dim iRow As Integer
Dim iCol As Integer
Dim iLastRow As Long
For iRow = 9 To 20
For iCol = 4 To 22
If Sheets(AuditWS).Cells(iRow, iCol).Value <> Sheets(LiveWS).Cells(iRow, iCol).Value Then
iLastRow = Sheets(AuditWS).Cells(Rows.Count, 1).End(xlUp).Row
Sheets(AuditWS).Cells(iLastRow + 1, 1) = "Cell(" & CStr(iRow) & "," & CStr(iCol) & ") " _
& "changed from '" & Sheets(AuditWS).Cells(iRow, iCol).Value & "' " _
& "to '" & Sheets(LiveWS).Cells(iRow, iCol).Value & "'"
Sheets(AuditWS).Cells(iRow, iCol) = Sheets(LiveWS).Cells(iRow, iCol).Value
End If
Next iCol
Next iRow
iLastRow = Sheets(AuditWS).Cells(Rows.Count, 1).End(xlUp).Row
Sheets(AuditWS).Cells(iLastRow + 1, 1) = "Workbook opened by " & Environ("USERNAME") _
& " on " & Format(Now(), "dd/mm/yyyy") & " at " & Format(Now(), "hh:nn:ss")
ActiveWorkbook.Save
End Sub
You sheet events to track changes.
behind your sheet1 try something like this
Option Explicit
Public bLog As Boolean
Private Sub Worksheet_Change(ByVal Target As Range)
If bLog Then
''''' YOUR Logging code here or a call to logging routine
End If
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
bLog = Not IsEmpty(Target.Value2)
End Sub