VBA根据特定单元格值重命名电子表格

时间:2018-06-15 14:07:58

标签: excel vba excel-vba

我想根据特定的单元格值重命名我的电子表格。 例如,我的不同电子表格的单元格A1如下:

  • 电子表格1:发票120894,Att。:LVM& TPM,ATM用户名
  • 电子表格2:发票120896,Att:TAM TAM,ATM用户名

我想在我的电子表格中给出单元格A1中的名称,例如LVM& TPM和TAM TAM。

有人可以帮忙吗?

我找到了一个有助于重命名的代码,但我不确定如何忽略周围的值和特殊字符:

   Sub RenameSheet()

 'VARIABLES DECLARATION
  Dim rs As Worksheet
  Dim new_name As String, tmp_new_name As String
  Dim counter As Integer: counter = 0
  Dim counter1 As Integer: counter1 = 1
  Dim allNames As Object

  'CODE
  Set allNames = CreateObject("Scripting.Dictionary")

  For Each rs In Sheets
'FIRST, LET'S PARSE THE NAME "LAST NAME" + ", " + "NAME INITIAL" + "."
new_name = Split(rs.Range("A1"), " ")(1) 
'CHECK IF IT EXISTS
If allNames.Exists(new_name) Then
    'ADD A COUNTER "(N)" UNTIL IT DOESN'T EXIST ANYMORE
    tmp_new_name = new_name
    Do While allNames.Exists(tmp_new_name) <> False
        tmp_new_name = new_name & " (" & counter1 & ")"
        counter1 = counter1 + 1
    Loop
    counter1 = 1
    new_name = tmp_new_name
End If
'RENAME
rs.Name = new_name
counter = counter + 1
'KEEP THE NAME STORED IN MEMORY (INTO THE DICTIONARY)
allNames.Add rs.Name, counter
Next rs
End Sub

谢谢!

2 个答案:

答案 0 :(得分:1)

这是一个快速子例程,用于从您开始使用的字符串中提取所需的详细信息,前提是它们始终采用相同的格式,对不起,我无法详细说明在我离开工作的这个时候,我希望你能将它应用到你的代码中。

Sub f()

Dim x As String
Dim n As String

    x = "Invoice 120894, Att.:LVM & TPM , ATM Username"
    n = Left(x, Len(x) - InStr(1, x, ","))
    n = Trim(Right(n, Len(n) - InStr(1, n, ":")))

    MsgBox n

End Sub

答案 1 :(得分:1)

这是一个很好的例子。使用字符串Hack&amp; Slash,你总是要记住字符串的格式,有时必须使用它来使它恰到好处。

Private Sub this()
    Dim this$: this = "Invoice 120894, Att.:LVM & TPM , ATM Username"
    this = Mid(this, InStr(1, this, ":") + 1, Len(this) - InStrRev(this, ",") - 3)
    Debug.Print ; this
End Sub

b / c我觉得你对此非常陌生,我想扩展我的例子,以便你能理解它在做什么

Private Sub this()
    Dim this$: this = "Invoice 120894, Att.:LVM & TPM , ATM Username"
    '                  123456789012314567890123456789012345678901234
    this = Trim(this)
        'String to use       starting point           Length of extracted string
    this = Mid(this, InStr(1, this, ":") + 1, Len(this) - InStrRev(this, ",") - 3)
    '                start at position 21          to position 29
    Debug.Print ; this
End Sub

看看这是否有帮助 - 你需要能够告诉编译器在哪里找到你想要操作的值。

Private Sub this()
    Dim this$
    this = ThisWorkbook.worksheets("yourworksheetname").Range("A1").Value
    this = Mid(this, InStr(1, this, ":") + 1, Len(this) - InStrRev(this, ",") - 3)
    Debug.Print ; this
End Sub