2017-04-07 54 views
0

首先,我很抱歉在这里发布这个问题。这个问题更多的是数学,而不是编程,但我不知道其他地方寻求帮助。基本上,我的代码通过使用字母和数字,1A,1B,1C,1D等来标记由用户突出显示的选择。有20种不同的样式(1乘1标签到20乘20标签)来标记所选单元格。如果我在第一次选择时选择了更大的数字(例如5),并且第一次选择在3A时完成(标签将如下所示:开始:1A 1B 1C 1D 1E 2A 2B 2C 2D 2E 3A,接下来的选择选择2作为第二个选择,标签将是不正确的,如下所示:3B 3C 3D 3E直到3Z,并且将持续到最后一个单元为8号,只有正确的标签应该是这样的:4A 4B 5A 5B 6A 6B。我什至不知道。是错误的代码,因此我需要你的帮助预先感谢您这些代码,我只是选择风格1只2,在代码的唯一不同的是数量:错误的标签使用宏Excel

Public A, B As Integer 

Sub AutoLabel() 

'to label the cell in term of 1A and etc 
A = 1 
B = 1 
End Sub 

Sub LabelTest() 
Dim Cell As Range 

With Selection 

' allign text so that it is centered between the top and bottom of the cell 
.HorizontalAlignment = xlCenter 

' allign text so that it is centered between the left and right of the cell 
.VerticalAlignment = xlCenter 

SR = .Row 
SC = .Column 
LR = SR + .Rows.Count - 1 
LC = SC + .Columns.Count - 1 
End With 

' to input the first cell as 1A, and next cell as 1B and etc 
For Each Cell In Selection 
Cell.value = B & Mid("ABCDEFGHIJKLMNOPQRSTUVWXYZ", A, 1) 
A = A + 1 
If A = 2 Then A = 1: B = B + 1 

Next Cell ' run next selected cell by user 

End Sub 
Sub LabelTest2() 
Dim Cell As Range 

With Selection 

' allign text so that it is centered between the top and bottom of the cell 
.HorizontalAlignment = xlCenter 

' allign text so that it is centered between the left and right of the cell 
.VerticalAlignment = xlCenter 

SR = .Row 
SC = .Column 
LR = SR + .Rows.Count - 1 
LC = SC + .Columns.Count - 1 
End With 

' to input the first cell as 1A, and next cell as 1B and etc 
For Each Cell In Selection 
Cell.value = B & Mid("ABCDEFGHIJKLMNOPQRSTUVWXYZ", A, 1) 
A = A + 1 
If A = 3 Then A = 1: B = B + 1 

Next Cell ' run next selected cell by user 
End Sub 

I asked the same question here but no reply

回答

0

首先,我做不要认为你的问题根本就是堆栈溢出。

如果我你的问题理解正确的话,下面应该工作:

Const ALPHABET As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 

Function getLabelNumber(ByVal labelNumber As Integer, ByVal labelsPerPage As Integer) As String 
    getLabelNumber = ((labelNumber - 1) \ labelsPerPage) + 1 & Mid(ALPHABET, ((labelNumber - 1) Mod labelsPerPage) + 1, 1) 
End Function 

然后说,你想你的细胞标记1A至1H,2A至2H和依此类推,直到10H,你只需要跟踪单个计数器(我们称之为i)并获取每个标签字符串getLabelNumber(i, 8)

您的代码如下可能能够利用这样的:

Dim cellCount As Integer, numCols As Integer 
numCols = Selection.Columns.Count 
For Each cell In Selection 
    cellCount = cellCount + 1 
    cell.Value = getLabelNumber(cellCount, numCols) 
Next cell 
+0

谢谢你的快速援助。但是,你能告诉我在编码中应该在哪里放置函数吗? – RainyDay

+0

或者更好,给我提供完整的编码,因为我对如何使用函数有点困惑。谢谢。 – RainyDay

+0

声明常量和你的'Sub'之外的函数。我用一个更好地说明你如何称呼它的片段更新了答案。 – jsheeran