2017-04-07 75 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