将字符串转换为列命名范围

时间:2016-03-11 22:08:51

标签: excel vba excel-vba

我想将列号和字符串传递给在字符串后面指定指定列的sub。例如,如果我的子调用是nameColumn(1," Some Name"),那么子名称列1" SomeName"。

我的代码:

Sub nameColumn(colNum as Integer, passedString as String)

    Dim ws As Worksheet
    Dim colName As String

    Set ws = Sheets("Sheet1")

    'remove any spaces from the string
    colName = Replace(passedString, " ", "")
    'name the column
    ws.Columns(colNum).Name = colName

End Sub

我意识到我试图在字符串之后命名范围。如何转换字符串以将其用作名为range的列?

2 个答案:

答案 0 :(得分:2)

您的代码缺少一条重要的行(请参阅"指定ws对象"),否则它应该可以正常工作:

Sub nameColumn(colNum As Integer, passedString As String)
    Dim ws As Worksheet

    'remove any spaces from the string
    colName = Replace(passedString, " ", "")

    ' specify ws object, for example the first one
    Set ws = Worksheets(1)

    'name the column
    ws.Columns(colNum).Name = Replace(passedString, " ", "")

End Sub

    Sub Test()
        Call nameColumn(2, "TestName")
    End Sub

示例Sub Test()将分配字符串" TestName"作为整个第二列的名称(工作表索引为1,列" B")。

以简化形式,您可以省略Worksheet对象的显式集合,从而产生如下所示的相当紧凑的代码段:

Sub nameColumn(colNum As Integer, passedString As String)
    'remove any spaces from the string
    colName = Replace(passedString, " ", "")

    'name the column
    Columns(colNum).Name = Replace(passedString, " ", "")
End Sub

希望这可能会有所帮助。

答案 1 :(得分:1)

考虑:

Sub nameColumn(colNum As Integer, passedString As String)

    Dim colName As String

    'remove any spaces from the string
    colName = Replace(passedString, " ", "")
    'name the column
    Cells(1, colNum).EntireColumn.Name = colName

End Sub

Sub main()
    Call nameColumn(1, "whatever")
End Sub

enter image description here

您发布的代码几乎是正确的。您需要Set ws