如何在VBA中设置工作表名称?

时间:2017-10-28 10:09:19

标签: excel vba excel-vba

我在使用此代码设置我可以想象的工作表时遇到一些问题,因为我没有dim as workbook但我尝试使用Sub CreateSheet() Set tsheet = ThisWorkbook.Sheets("For Save") Dim th As String Dim thf As String Dim thfs As Workbook th = Replace(tsheet.Range("A11").Value, "/", "-") thf = "SAVE" & " " & th & " " & tsheet.Range("A3").Value With ThisWorkbook .Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = thf Set thfs = ThisWorkbook.Sheets(thf) tsheet.Ranges("A1:R201").Copy qsheet.Columns("A").PasteSpecial xlPasteValues End With End Sub 无效。

我试着一步一步地走,“thf”中有正确的字符串。

<div class="content-canvas">
    <div class="horizontal-section" id="blog">
        <h1>Blog</h1>
        <div id="divRss">
            <ul class="feedEkList">
                <li>
                    <div class="itemTitle"><a href="#</a></div>
                    <div class="itemDate">10/16/2017</div>
                    <div class="itemContent">Some text</div>
               </li>
               <li>
                   As above
               </li>
            </ul>
        </div>
        <a href="##" target="_blank">Read more</a>
    </div>
    <div class="horizontal-section" id="upcoming">
    ...
    </div>
</div>

2 个答案:

答案 0 :(得分:0)

  1. Worksheet使用thfs变量,或将其包含在With中,就像我在下面所做的那样
  2. 工作表名称只能是31个字符,因此最好检查
  3. 试试这个:

    Sub CreateSheet()
        Dim tsheet As Worksheet
        Dim th As String, thf As String
    
        Set tsheet = ThisWorkbook.Sheets("For Save")
        th = Replace(tsheet.Range("A11").Value, "/", "-")
        thf = "SAVE" & " " & th & " " & tsheet.Range("A3").Value
    
        With ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
            .Name = Left(thf, 31) 'remove if you're sure the length won't be over 31 characters
            tsheet.Ranges("A1:R201").Copy
            .Range("A1").PasteSpecial xlPasteValues
        End With
    End Sub
    

答案 1 :(得分:0)

转贴为答案。您已在以下语句thfs中将Dim thfs As Workbook声明为工作簿,但后来尝试SET将其作为工作表。尝试将其更改为Dim thfs As Worksheet