0

In my macro, I will select a cell and insert the Formula. I will insert inside a Table. So it can be automatically draged down. But the problem is My Sheet name "December" will be changed every month. Next month it will be "January" and so on. How to change the formula.

=INDEX(Product!$L:$L; MATCH(December!$A3; Product!$I:$I; 0);COLUMNS($A:A))

The sheet name will be changed manually. Help me

Sub Macro1()
Range("Q3").Value = "=INDEX(Product!C12, MATCH(December!RC1, Product!C9, 0),COLUMNS(C1:C[-16]))"
End Sub
braX
  • 11,506
  • 5
  • 20
  • 33
Deepak
  • 473
  • 1
  • 10
  • 32

4 Answers4

2

Put this in the worksheet module:

Private Sub Worksheet_Activate()        
    Me.Name = Format(Date, "MMMM")        
End Sub

Thus the name of the worksheet would be changed every time you click on it, depending on the current month. For the short version of the name, use Format(Date, "MMM").


If you want to get the ActiveSheet name from an Excel formula:

=MID(CELL("filename",A1),FIND("]",CELL("filename",A1))

What Excel formula returns the sheet name?

Vityata
  • 42,633
  • 8
  • 55
  • 100
2

Use MonthName(Month(Date)) in your vba

Range("Q3").Value = "=INDEX(Product!C12, MATCH(" & MonthName(Month(Date)) & "!RC1, Product!C9, 0),COLUMNS(C1:C[-16]))"

This will currently produce:

=INDEX(Product!C12, MATCH(December!RC1, Product!C9, 0),COLUMNS(C1:C[-16]))

Or you could use INDIRECT in your excel formula

=INDEX(Product!C12, MATCH(INDIRECT(TEXT(NOW(), "mmmm")& "!RC1",False), Product!C9, 0),COLUMNS(C1:C[-16]))

This way it'll update automatically without having to run any vba. However, INDIRECT is a volatile function so it can cause slowness in your workbook.

Tom
  • 9,725
  • 3
  • 31
  • 48
2

Since all you need is the Month as a String of the date, simply use Format(Date, "mmmm")

Implemented in your VBA code:

Range("Q3").Value = "=INDEX(Product!C12, MATCH(" & Format(Date, "mmmm") & "!RC1, Product!C9, 0),COLUMNS(C1:C[-16]))"
Shai Rado
  • 33,032
  • 6
  • 29
  • 51
1

You can get the name of the current/active sheet using

wsname = ActiveSheet.Name

Or if the sheet you need is always say the 3rd sheet then

wsname = Sheets(3).Name

But you can't just replace "December" with this variable, you need to build your formula as a text string. Your test has to be in quotes, while the variable is not.

Sub Macro1()
wsname = ActiveSheet.Name
Range("Q3").Value = "=INDEX(Product!C12, MATCH(" & wsname & "!RC1, Product!C9, 0),COLUMNS(C1:C[-16]))"
End Sub
mooseman
  • 1,997
  • 2
  • 17
  • 29