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