我尝试在Excel中使用宏命名单元格。这是代码:
Sub setHeader()
Dim Wb As Workbook
Dim Ws As Worksheet
Dim Cell As Range
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim l As Integer
i = 0
j = 0
k = 0
l = 0
Dim MyColumnRange As Range
Dim MyRowRange As Range
Dim MyCellRange As Range
Set MyColumnRange = ActiveSheet.Range("E7:V8")
Set MyRowRange = ActiveSheet.Range("B10:B16")
Set MyCellRange = ActiveSheet.Range("E10:V16")
Dim MyColumnName As String
Dim MyRowName As String
Dim MyCellName As String
MyColumnName = "HC_"
MyRowName = "HL_"
MyCellName = "?"
For Each Cell In MyRowRange
Cell.Name = MyRowName + CStr(j)
j = j + 1
Next Cell
For Each Cell In MyColumnRange
If Not IsEmpty(Cell.Value) Then
Cell.Name = MyColumnName + CStr(i)
i = i + 1
End If
Next Cell
For Each Cell In MyCellRange
Cell.Name = MyRowName + CStr(k) + MyCellName + MyColumnName + CStr(l)
If l = (MyCellRange.Columns.Count - 1) Then
l = 0
k = k + 1
Else
l = l + 1
End If
Next Cell
End Sub
我在MyColumnRange
和MyCellRange
中的命名工作得很好,但对于MyRowRange
我有错误
“对象范围的方法名称失败”
我不明白为什么。
答案 0 :(得分:0)
在MyRowRange中命名单元格时:
For Each Cell In MyRowRange
Cell.Name = MyRowName + CStr(i)
j = j + 1
Next Cell
您使用极其命名的变量i
命名它们,但是您正在增加非常命名的变量j
。可能你的意思是Cell.Name = MyRowName + Cstr(j)
答案 1 :(得分:0)
所以,你真的不需要转换为字符串,尝试使用&而不是像这样的例子:
For j = 1 to MyRowRange.cells.count
MyRowRange.cells(j).Name = MyRowName & j
Next j
我为每个循环改变了你的方式(这很好),只是为了一个其他方法的例子......