将月份名称(法语)转换为月份号码

时间:2018-05-15 15:12:50

标签: vba excel-vba excel

我有一个excel,其中每月创建一个工作表,名称为kpi_monthname,其中月份名称包含该月份的前3个字符。就像五月一样,它显示为kpi_mai或四月显示为kpi_avr。月份名称是法语。我想拿这个月的名字并将其转换为月号。如果月份名称是英文,我有此转换的代码,但对于法语,它显示错误。

如果我可以将月份名称转换为英语,正在创建月份名称或将月份名称(以法语显示)转换为月份号码,请告诉我。这两种解决方案都适用于我。

在为当月创建新工作表时,请查看以下代码:

 premier_jour = DateSerial(Year(Date), Month(Date), 1)
 dernier_jour = DateSerial(Year(Date), Month(Date) + 1, 1)
 deb_period_curr = Format(premier_jour, "mmm")

 With ThisWorkbook
    .Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = "analysis_kpi " & deb_period_curr
 End With

如需将月份名称转换为月份号码,请参阅以下代码:

 month_nam = Right(worksheet1.Name, 4)
 month_num = Evaluate("=MONTH(1&" & Chr(34) & month_nam & Chr(34) & ")")
 month_num = WorksheetFunction.Text(month_num, "00")

5 个答案:

答案 0 :(得分:3)

  

如果我可以将月份名称转换为英语,请告诉我   正在创建

这很容易,将月份名称更改为英语(或其他语言)替换:

deb_period_curr = Format(premier_jour, "mmm")

(前3个字母):

deb_period_curr = WorksheetFunction.Text(premier_jour, "[$-409]mmm")

或(全名):

deb_period_curr = WorksheetFunction.Text(premier_jour, "[$-409]mmmm")

TEXT公式支持国家/地区代码。 409是美国英语,但您可以找到语言列表和更多信息here

要获得2位数的月份数,您可以使用例如:

deb_period_curr = Format(premier_jour, "mm")

答案 1 :(得分:1)

使用Dictionary对象定义法语月份:

sub m()
Dim months As New Scripting.Dictionary
    months.Add Key:="kpi_mai", Item:=5
    months.Add Key:="kpi_avr", Item:=4
    Debug.Print months("kpi_avr")
End Sub

我加了两个月你提到的因为我没有'知道名字......
您必须在项目中添加对Microsoft Scripting Runtime的引用

答案 2 :(得分:1)

使用数组和匹配的轻微变化

application.match("fev",Array("Jan","Fev","Mar","Avr","Mai"),0)

答案 3 :(得分:0)

您还可以使用数组存储月份名称,这就是我对英文月份名称的处理方式:

Dim monthNames as variant

monthNames = Array(,"January","February","March","April","May","June","July","August","September","October","November","December")

获得第5个月的名字:

Debug.Print monthNames(5)

获取字符串“May”的月份数:

Dim nCounter as Long
Dim myMonthString as String

myMonthString = "May"

For nCounter = LBound(monthNames) to UBound(monthNames)
    If monthNames(nCounter) = myMonthString then
        Debug.Print nCounter 'month number
        Exit For
    End if
Next nCounter

答案 4 :(得分:0)

我通常遇到同样的问题(使用葡萄牙语版的MS Excel)。通常我会用简单的Select Case将名称(葡萄牙语)转换为月份数(或相反):

Dim MonthStr as String
Dim MonthNum as Integer

MonthStr = Cells(1, 1).Text 'Location of the month name

Select Case MonthStr
    Case "Janeiro": MonthNum = 1
    Case "Fevereiro": MonthNum = 2        
    Case "Março": MonthNum = 3
    Case "Abril": MonthNum = 4
    Case "Maio": MonthNum = 5
    Case "Junho": MonthNum = 6
    Case "Julho": MonthNum = 7
    Case "Agosto": MonthNum = 8
    Case "Setembro": MonthNum = 9
    Case "Outubro": MonthNum = 10
    Case "Novembro": MonthNum = 11
    Case "Dezembro": MonthNum = 12
End Select

诚实我认为这是解决这个问题最简单的方法......