I want to write a vba code that looks for a sheet with a name that corresponds to the…
- User
I want to write a vba code that looks for a sheet with a name that corresponds to the current month and year. If the sheet does not exist, then it will create it. For example if the current Month today March in the Year 2023, then there should be a sheet named Mar23.
- Assistant
Here's a VBA code that should accomplish what you're asking for:
codeSub CreateMonthSheet() Dim strMonth As String Dim strYear As String Dim strSheetName As String strMonth = Format(Date, "mmm") strYear = Format(Date, "yy") strSheetName = strMonth & strYear On Error Resume Next Sheets(strSheetName).Select If Err.Number <> 0 Then Sheets.Add.Name = strSheetName End If On Error GoTo 0 End SubThis code first gets the current month and year using the
Formatfunction. It then concatenates them together to form the sheet name.It then attempts to select a sheet with the same name using
Sheets(strSheetName).Select. If there's an error (i.e. the sheet doesn't exist), then it creates a new sheet with that name usingSheets.Add.Name = strSheetName. - User
On Workbook Open, I need to write a vba code that asks if I would like to clear data from the worksheets. If I say NO, the data is left alone. If I say YES, the values in A2:B21 in the following sheets are all set to "". Sheets Prem MG, Prem SU, Prem Cl, Prem Cl, Prem AA, and Prem PM. In sheet Observe, the values in A2:E30 are all set to "".
- Assistant
Here's some VBA code that should accomplish what you're asking for:
codePrivate Sub Workbook_Open() Dim response As Integer response = MsgBox("Would you like to clear data from the worksheets?", vbYesNo + vbQuestion, "Clear Data") If response = vbYes Then ClearData Sheets("Prem MG") ClearData Sheets("Prem SU") ClearData Sheets("Prem Cl") ClearData Sheets("Prem AA") ClearData Sheets("Prem PM") ClearData Sheets("Observe") End If End Sub Sub ClearData(sheet As Worksheet) sheet.Range("A2:B21").Value = "" If sheet.Name = "Observe" Then sheet.Range("A2:E30").Value = "" End If End Sub