使用宏Excel的标签错误

时间:2017-04-07 06:38:26

标签: excel

首先,我很抱歉在这里发布这个问题。这个问题更多的是数学,而不是编程,但我不知道其他地方寻求帮助。基本上,我的代码用于标记用户使用字母和数字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,代码中唯一不同的是数字:

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

1 个答案:

答案 0 :(得分:0)

首先,我认为你的问题根本不是Stack Overflow的主题。

如果我已正确理解您的问题,以下情况应该有效:

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
相关问题