VBA: Assign Worksheet with current date to an object - vba

A piece of my macro adds a new worksheet with the current date but when I want to assign the worksheet to an object it doesn't work. I get a
run time error 9
Dim shA As Worksheet
Set shA = Worksheets(Date)
Can anyone help?

You need to convert Date to a String format, depending on the format of your date.
Dim shA As Worksheet
Set shA = Worksheets(Format(Date, "dd.mm.yyyy"))

Considering that your computer date is in format DD.MM.YYYY, if you are looking to change the tab name of the worksheet, then it is like this:
ActiveSheet.name = Date()
or
shA.Name = Date()
Thus, you will get this:

Related

Getting the date format in VBA in the correct form

I am trying to reference a file that has the date of the previous Friday at the end in the form of mm.dd.yy.
I need to now take that date and add it to the end of a string, to end of a string in order to open select the other workbook. This is what I have right now.
File Name:
Submittals Wk Ending 06.02.17.xlsx
This is what I have so far
Dim wrbk As String
Dim weekdate As String
range("a1").value="=TODAY()-WEEKDAY(TODAY())-1"
weekdate = Range("a1").Value
'range("b1").value="06.02.17"
'weekdate = Range("b1").Value
msgbox weekdate 'use to check what the date format is
wrbk = "Submittals Wk Ending " & weekdate
Windows(wrbk & ".xlsx").Activate
When I read it from B2 with the typed in format of 06.02.17 it works, however no matter what I do, I cannot get it to read it from A1 because it changes the format to m/d/yyyy. I have tried to copy it and paste as value. Nothing seems to work.
I have the other workbook open as well when I try to run it.
Any ideas? Thanks!
To get the previous Friday of any date, try below UDF. This should work fine if the Date NumberFormat is same as your System's Date format. The key is the CDate() which converts according to System's Date format which Office apps defaults to.
Option Explicit
Function GetLastFridayDate(AnyDate As Variant) As Date
Dim dInput As Date, dLastFriday As Date
dInput = CDate(AnyDate)
dLastFriday = dInput - Weekday(dInput) + vbFriday - IIf(Weekday(dInput) > vbFriday, 0, 7)
GetLastFridayDate = dLastFriday
End Function
Try
Range("A1").Value = Format$(Date - Weekday(Date) - 1, "MM.DD.YY")

Excel VBA - Month in "mmmm" format

I need to use the current and the previous month in "mmmm" format, and the best solution I found is MonthName(Month(Date)).
However, Excel keeps giving me:
Compile Error: Object Required
And it's driving me crazy. I'm pretty new to VBA so can anyone explain what I am doing wrong here?
Sub test()
Dim CurrentMonth As Variant
Dim PreviousMonth As Variant
Set CurrentMonth = MonthName(Month(SetupSheet.Range("C9"))) '<-------HERE
Set PreviousMonth = MonthName(Month(SetupSheet.Range("C9") - 1))
...
End Sub
You don't need to use Set. You only use that if you are passing Object to a variable.
This line returns a String and not an Object (e.g. Range, Worksheet, Chart, etc.)
MonthName(Month(SetupSheet.Range("C9"))) 'if C9 contains a valid date format
So to pass it to CurrentMonth variable, simply assign it using = sign:
CurrentMonth = MonthName(Month(SetupSheet.Range("C9")))
Lowercase 'm' is minute. Uppercase 'M' is for month.

Excel Cell Location Using Row And Column Numbers VB.net

I have a vb.net program that is reading and writing to an excel file. I need to use the "Range" function for a specific task, but it requires the actual value of the cell. All I have is the Row and Column number which varies depending on what the user is doing. How do I get the actual cell location based off of the row/column number without hard coding it.
Example:
Row 1, Column 1 = "A1"
Row 5, Column 27 = "AA5"
In vb.net you need to convert each object explicitly as follows.
CellValue = CType(CType(CType(ExcelApp.Workbooks("WorkbookName"), Excel.Workbook).Worksheets("SheetName"), Excel.Worksheet).Cells(rowNum, colNum), Excel.Range).Value
Ideally you would already have variables for the workbook and worksheet which would make this previous statement more readable. For example:
Dim wbk As Excel.Workbook = CType(ExcelApp.Workbooks("WorkbookName"), Excel.Workbook)
Dim wst As Excel.Worksheet = CType(wbk.Worksheets("SheetName"), Excel.Worksheet)
Dim CellValue As Object = CType(wst.Cells(rowNum, colNum), Excel.Range).Value
Note: Substitute your Excel Application variable for ExcelApp.
Workbook("Name").Sheets("Name").Cells(RowVariable, ColVariable).Address

Excel - Conditional macro / VBA script

I'm trying to automate a report that for a customer and I'm a bit stuck with one of the hurdles that needs to overcome, I have some ideas but am new to VB programming.
The requirement is to copy a range of cells from one sheet to another, but the destination needs to change depending on the current date. Using a general example I'm trying to achieve the following:
If the date is the 1st of the month, the destination range is B2:F3, if it is the 2nd then the destination range is B4:F5, if the 3rd then destination is B6:F7....... if the 31st then the destination is B62:F63, the source ranges are static.
I figured I could probably achieve this by writing a huge script which contained an IF statement for each day of the month, but I was hoping I could be a bit smarter and use variables to assign the row references at the beginning of the script then just sub them back into the select/copy statements.
Absolutely you can.
Dim x as Integer
Dim daymonth as Integer
Dim rw as String
daymonth = CInt(Format(date, "d"))
x = daymonth * 2
rw = CStr(x)
Now you can use range like:
Range("D" & rw & ":F" & CStr(x + 1))
Just an example. Then since the number is constant between the two ranges just add that number to x and use it in the range.
You may want following subroutine.
Sub copyDataDependOnDatte()
Dim today As Date, dayOfToday As Integer
Dim sWS As Worksheet, dWS As Worksheet
'set two worksheets to variables
Set sWS = Worksheets("source") 'Worksheet which has data to be copied
Set dWS = Worksheets("destination") 'Worksheet which is used to record data of days.
' get day of today
today = Now() 'get date of today
dayOfToday = Day(today) ' get day of today
Range(sWS.Cells(2, 2), sWS.Cells(3, 6)).Copy 'copy B2:F3 of worksheet "source"
dWS.Cells(dayOfToday * 2, 2).PasteSpecial ' paste to worksheet "destination" at place determined by day of today
End Sub
In this code,I assumed following for writing concreat code.
"source" is name of worksheet which contains the data to be copied
"destination" is name of worksheet which records tha data copied from "source" worksheet
Data to be copied is exist at "B2:F3" of worksheet "source"
Please change worksheets' names to real names of your data.
Place of data to be copied is described as "Range(sWS.Cells(2, 2), sWS.Cells(3, 6))" in the code.
cells(2,2) means cell on 2nd row and 2nd column, i.e. "B2".
Cells(3,6) means cell on 3rd row and 6th column, i.e. "F3".
Plese correct place to fit your data.

Problems with VLOOKUP in VBA

All,
I'm trying to use vlookup in a simple VBA function, but it is continually returning #VALUE!
Here is the code:
Public Function getAreaName(UBR As Integer) As String
Dim result As String
Dim sheet As Worksheet
Set sheet = ActiveWorkbook.Sheets("UBR Report")
' check level 3 then 2 then 4 then 5
result = Application.WorksheetFunction.VLookup(UBR, sheet.Range("UBRLookup"), Application.WorksheetFunction.Column(sheet.Range("UBRLookup[Level 3]")), False)
getAreaName = result
End Function
Any thoughts?
I'm not quite sure what you're trying to do with the "UBRLookup[Level 3]" reference, but as Joseph has pointed out, that's the bit that you're doing wrong.
[ is not a valid character for a named range in Excel.
The column that you're referencing needs to be a numeric value, the offset from the start of the table-array you've defined as your named range.
The below should work, provided the column you want to pull out is the second column in your named range (e.g. what you're referring to as [level 3] is in the second column).
Public Function getAreaName(UBR As Integer) As String
Dim result As String
Dim sheet As Worksheet
Set sheet = ActiveWorkbook.Sheets("UBR Report")
result = Application.WorksheetFunction.VLookup(UBR, sheet.Range("UBRLookup"), 2, False)
getAreaName = result
End Function
Update:
I've had a look at Excel 2007 and from what I can see the column function isn't exposed as an Application.WorksheetFunction.
You can use it on the sheet with =Column(D4), but when trying to autocomplete within the vba editor, the function isn't there. This may be due to a difference in versions, so I'll ignore that for now.
It still definitely seems like you're mis-using the third argument. If you really don't want to use the number reference we need to find out where the function is going wrong.
A few tests along the lines of
Debug.Print Application.WorksheetFunction.Column(D4)
Debug.Print sheet.Range("UBRLookup[Level 3]")
should hopefully help to show you exactly where it's going wrong - I believe that it will object to both of the above, but if it returns some useful information then we may be a step closer to your solution.
Break you function up into more pieces. Then debug it and make sure every piece is set up the way you expect.
Example:
Public Function getAreaName(UBR As Integer) As String
Dim result As String
Dim sheet As Worksheet
Set sheet = ActiveWorkbook.Sheets("UBR Report")
Dim range as Range = sheet.Range("UBRLookup")
Dim column as Column = Application.WorksheetFunction
.Column(sheet.Range("UBRLookup[Level 3]"))
result = Application.WorksheetFunction.VLookup(UBR, range, column, False)
getAreaName = result
End Function
In fact, just by doing that I noticed something weird. You use a range in two different places, but in one place you're looking for UBRLookup, and in another you're looking for UBRLookup[Level 3], is that correct?
I am disturbed by
Dim column as Column =
Application.WorksheetFunction.Column(sheet.Range("UBRLookup[Level 3]"))
You should Dim column as long, I think, and maybe use a variable name that's not to be confused with a property, like lngCol.
This part: sheet.Range("UBRLookup[Level 3]") is suspect as "UBRLookup[Level 3]" is not a valid range name.