【问题标题】:Selecting a sheet with a dynamic name which contains a date选择具有包含日期​​的动态名称的工作表
【发布时间】:2021-02-09 04:03:28
【问题描述】:

我一直在尝试选择一张名为“SYS 6.10.2020”的工作表。但是,此表每周更改其日期。是否有 VBA 代码可以让代码根据今天的日期选择工作表?

【问题讨论】:

  • 也许通常引用它的索引号?喜欢工作表(1) trumpexcel.com/vba-worksheets
  • 如果您最新的工作表位于所有其他工作表的末尾(右侧),那么您可以使用Worksheets(Worksheets.Count)

标签: excel vba date dynamic


【解决方案1】:

工作表名称

守则

Option Explicit

' If it is the only worksheet that starts with "SYS ", "sys "...
Sub PartialMatch()
        
    Const wsName As String = "SYS "
    
    Dim wb As Workbook
    Set wb = ThisWorkbook
    
    Dim ws As Worksheet
    For Each ws In wb.Worksheets
        If StrComp(Left(ws.Name, Len(wsName)), wsName, vbTextCompare) = 0 Then
            Exit For
        End If
    Next
    
    If ws Is Nothing Then
        'MsgBox "Worksheet starting with '" & wsName _
             & "' not found.", vbCritical, "Fail"
        Debug.Print "Worksheet starting with '" & wsName & "' not found."
        Exit Sub
    End If
    
    ' Continue with code...
    Debug.Print ws.Name
    
End Sub
        
Sub ExactMatch()
        
    Dim wb As Workbook
    Set wb = ThisWorkbook
    
    Dim wsName As String
    wsName = "SYS " & Replace(Format(Date, "d/m/yyyy"), "/", ".")
    
    On Error Resume Next
    Dim ws As Worksheet
    Set ws = wb.Worksheets(wsName)
    On Error GoTo 0
    
    If ws Is Nothing Then
        'MsgBox "Worksheet '" & wsName & "' not found.", vbCritical, "Fail"
        Debug.Print "Worksheet '" & wsName & "' not found."
        Exit Sub
    End If
    
    ' Continue with code...
    Debug.Print ws.Name
    
End Sub

【讨论】:

    【解决方案2】:

    静态字符串

    您可以通过向Sheets 函数提供日期(以适当的格式格式化)来做到这一点。

    快速示例:

    Sheets("SYS 6.10.2020").Select
    

    动态字符串

     Sub Task1()
    
    Dim myDate
    myDate = Date
       
       MsgBox myDate
       
    Dim LValue As String
     LValue = "SYS " & Format(myDate, "dd.mm.yyyy")
    
    MsgBox LValue
    
    
     Sheets(LValue).Activate
    
    End Sub
    

    如果每周只添加一张工作表,您可以使用 vba 中的日历查找最后日期(例如上周一)并从中生成名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-25
      • 1970-01-01
      • 2019-12-03
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多