vba - 将字符串转换为名为范围的列

标签 vba excel

我想将列号和字符串传递给在字符串之后命名指定列的子项。例如,如果我的子调用是 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 的列?

最佳答案

您的代码缺少重要的一行(请参阅“指定 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

sample 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

希望这可能会有所帮助。

关于vba - 将字符串转换为名为范围的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35950833/

相关文章:

java - 使用java从Excel文件的列中删除HTML标签

excel - 如何更改 VBA Excel 中显示用户窗体的值

excel - 使用vba过滤数据透视表中的行标签

vba - Access vba 检查文件是否存在

缺少 Java org.apache.poi.unsupportedfileformaexception

excel - 返回到按下按钮的工作表

excel vba-重写从循环中的公式返回的错误(类型不匹配)

c++ - RegQueryValueEx 的奇怪行为会返回另一个寄存器的值

css - word vba创建具有个性化风格的条目

VBA 宏 Excel