Programing

열 번호를 문자로 변환하는 기능?

crosscheck 2020. 6. 29. 08:04
반응형

열 번호를 문자로 변환하는 기능?


누구든지 숫자에서 열 문자를 반환 할 수있는 Excel VBA 기능이 있습니까?

예를 들어 100입력 하면을 반환해야합니다 CV.


이 함수는 주어진 열 번호에 대한 열 문자를 반환합니다.

Function Col_Letter(lngCol As Long) As String
    Dim vArr
    vArr = Split(Cells(1, lngCol).Address(True, False), "$")
    Col_Letter = vArr(0)
End Function

열 100의 테스트 코드

Sub Test()
    MsgBox Col_Letter(100)
End Sub

범위 객체를 사용하지 않으려는 경우 :

Function ColumnLetter(ColumnNumber As Long) As String
    Dim n As Long
    Dim c As Byte
    Dim s As String

    n = ColumnNumber
    Do
        c = ((n - 1) Mod 26)
        s = Chr(c + 65) & s
        n = (n - c) \ 26
    Loop While n > 0
    ColumnLetter = s
End Function

나를 위해 일하는 것은 다음과 같습니다.

Cells(Row,Column).Address 

그러면 $ AE $ 1 형식 참조가 반환됩니다.


** <code> </ code> <code> Columns (</ code> *** <code> Column Index </ code> *** <code>). Address </ code> <code> </ code> **

  • 예를 들어, MsgBox Columns( 9347 ).Address Returns ** <code> $ MUM : $ MUM </ code> ** .

열 문자 반환하려면 :Split((Columns(Column Index).Address(,0)),":")(0)

  • 예를 들어, MsgBox Split((Columns( 2734 ).Address(,0)),":")(0) Returns ** <code> DAD </ code> ** .

  더 많은 예



그리고 재귀를 사용하는 솔루션 :

Function ColumnNumberToLetter(iCol As Long) As String

    Dim lAlpha As Long
    Dim lRemainder As Long

    If iCol <= 26 Then
        ColumnNumberToLetter = Chr(iCol + 64)
    Else
        lRemainder = iCol Mod 26
        lAlpha = Int(iCol / 26)
        If lRemainder = 0 Then
            lRemainder = 26
            lAlpha = lAlpha - 1
        End If
        ColumnNumberToLetter = ColumnNumberToLetter(lAlpha) & Chr(lRemainder + 64)
    End If

End Function

이 작업을 수행하는 또 다른 방법입니다. Brettdj의 대답 은 이것을 생각하게 만들었지만이 방법을 사용하면 변형 배열을 사용할 필요가 없으므로 문자열로 직접 이동할 수 있습니다.

ColLtr = Cells(1, ColNum).Address(True, False)
ColLtr = Replace(ColLtr, "$1", "")

또는 이것으로 조금 더 작게 만들 수 있습니다.

ColLtr = Replace(Cells(1, ColNum).Address(True, False), "$1", "")

이것은 셀 객체에서 행 1을 참조하는 것에 달려 있습니다.


이것은 공식을 사용하여 사용할 수 있습니다.

=SUBSTITUTE(ADDRESS(1,COLUMN(),4),"1","")

요청 된대로 VBA 함수로 작성할 수도 있습니다.

Function ColName(colNum As Integer) As String
    ColName = Split(Worksheets(1).Cells(1, colNum).Address, "$")(1)
End Function

이것은 루프 대신 재귀를 사용 하는 robartsd의 답변 버전입니다 ( Jan Wijninckx의 한 줄 솔루션의 풍미와 함께 ).

Public Function ColumnLetter(Column As Integer) As String
    If Column < 1 Then Exit Function
    ColumnLetter = ColumnLetter(Int((Column - 1) / 26)) & Chr(((Column - 1) Mod 26) + Asc("A"))
End Function

나는 다음 입력으로 이것을 테스트했다.

1   => "A"
26  => "Z"
27  => "AA"
51  => "AY"
702 => "ZZ"
703 => "AAA" 
-1  => ""
-234=> ""

최신 업데이트 : 아래 기능을 무시하십시오. @SurasinTancharoen은에서 고장났다는 경고 메시지를 표시했습니다 n = 53.
관심있는 사람들을 위해 아래에 다른 깨진 값이 있습니다 n = 200.

의 특정 가치

모든 요구에 @brettdj 기능을 사용하십시오. 심지어 Microsoft Excel의 최신 최대 열 수 제한에서 작동 16384합니다.XFD

여기에 이미지 설명을 입력하십시오

업데이트 종료


아래 기능은 Microsoft에서 제공합니다.

Function ConvertToLetter(iCol As Integer) As String
   Dim iAlpha As Integer
   Dim iRemainder As Integer
   iAlpha = Int(iCol / 27)
   iRemainder = iCol - (iAlpha * 26)
   If iAlpha > 0 Then
      ConvertToLetter = Chr(iAlpha + 64)
   End If
   If iRemainder > 0 Then
      ConvertToLetter = ConvertToLetter & Chr(iRemainder + 64)
   End If
End Function

출처 : Excel 열 번호를 알파벳 문자로 변환하는 방법

에 적용

  • Microsoft Office Excel 2007
  • Microsoft Excel 2002 Standard Edition
  • Microsoft Excel 2000 Standard Edition
  • Microsoft Excel 97 Standard Edition

robertsd의 코드 는 우아하지만 미래를 보장 하기 위해 n의 선언을 long으로 변경하십시오.

매크로를 피하기 위해 수식을 원할 경우 여기에 702 열까지 작동하는 것이 있습니다.

=IF(A1>26,CHAR(INT((A1-1)/26)+64),"")&CHAR(MOD(A1-1,26)+65)

여기서 A1은 문자로 변환 할 열 번호를 포함하는 셀입니다.


Excel power를 사용하는 매우 간단한 방법 Range.Cells.Address이 있습니다.

strCol = Cells(1, lngRow).Address(xlRowRelative, xlColRelative)

행 1에서 원하는 열의 주소를 반환합니다 1.

strCol = Left(strCol, len(strCol) - 1)

너무 빠르고 강력하여 존재하는 열 주소를 반환 할 수 있습니다!

속성을 lngRow사용하여 원하는 열 번호로 대체 하십시오 Selection.Column!


의 @DamienFennelly의 답변을 기반으로하는 함수입니다 . 당신이 나에게 엄지 손가락을 포기하면 그에게도 엄지 손가락을 줘! :피

Function outColLetterFromNumber(iCol as Integer) as String
    sAddr = Cells(1, iCol).Address
    aSplit = Split(sAddr, "$")
    outColLetterFromNumber = aSplit(1)
End Function

사용할 수있는 간단한 라이너 하나입니다.

ColumnLetter = Mid(Cells(Row, LastColA).Address, 2, 1)

그것은 1 문자 열 지정에만 작동하지만 간단한 경우에 좋습니다. 독점적으로 2 글자로 지정 해야하는 경우 다음을 사용할 수 있습니다.

ColumnLetter = Mid(Cells(Row, LastColA).Address, 2, 2)

이것은 X 행, Y 열의 셀에 대한 하나의 코드 라인 내부의 열에 관계없이 작동합니다.

Mid(Cells(X,Y).Address, 2, instr(2,Cells(X,Y).Address,"$")-2)

고유하게 정의 된 이름이 "셀 이름"인 셀이있는 경우 :

Mid(Cells(1,val(range("Cellname").Column)).Address, 2, instr(2,Cells(1,val(range("Cellname").Column)).Address,"$")-2)

brettdj의 솔루션은 환상적으로 작동하지만 같은 이유로 잠재적 인 솔루션 으로이 문제를 겪고 있다면 대안 솔루션을 제공 할 것이라고 생각했습니다.

내가 겪고 있었던 문제는 MATCH () 함수의 출력을 기반으로 특정 열로 스크롤하는 것입니다. 열 번호를 열 문자 병렬로 변환하는 대신 참조 스타일을 A1에서 R1C1로 일시적으로 전환했습니다. 이렇게하면 VBA 기능을 사용하지 않고도 열 번호로 스크롤 할 수 있습니다. 두 가지 참조 스타일간에 쉽게 전환하려면이 VBA 코드를 사용하십시오.

Sub toggle_reference_style()

If Application.ReferenceStyle = xlR1C1 Then
  Application.ReferenceStyle = xlA1
Else
  Application.ReferenceStyle = xlR1C1
End If

End Sub

brettdj 답변에 더 나아가, 열 번호 입력을 선택적으로 만드는 것입니다. 열 번호 입력이 생략되면 함수는 함수를 호출하는 셀의 열 문자를 리턴합니다. 나는 이것을 또한 사용하여 달성 할 수 있다는 것을 알고 ColumnLetter(COLUMN())있지만, 똑똑하게 이해할 수 있다면 좋을 것이라고 생각했습니다.

Public Function ColumnLetter(Optional ColumnNumber As Long = 0) As String
    If ColumnNumber = 0 Then
        ColumnLetter = Split(Application.Caller.Address(True, False, xlA1), "$")(0)
    Else
        ColumnLetter = Split(Cells(1, ColumnNumber).Address(True, False, xlA1), "$")(0)
    End If
End Function

이 기능의 단점은 IF테스트 때문에 brettdj의 답변보다 매우 약간 느리다는 것 입니다. 그러나이 기능을 반복해서 많이 사용하면 이것이 느껴질 수 있습니다.


여기에 늦은 대답은 사용하는 단순한 접근 방식입니다 Int()If1-3 문자 컬럼의 경우 :

Function outColLetterFromNumber(i As Integer) As String

    If i < 27 Then       'one-letter
        col = Chr(64 + i)
    ElseIf i < 677 Then  'two-letter
        col = Chr(64 + Int(i / 26)) & Chr(64 + i - (Int(i / 26) * 26))
    Else                 'three-letter
        col = Chr(64 + Int(i / 676)) & Chr(64 + Int(i - Int(i / 676) * 676) / 26)) & Chr(64 + i - (Int(i - Int(i / 676) * 676) / 26) * 26))
    End If

    outColLetterFromNumber = col

End Function

Function fColLetter(iCol As Integer) As String
  On Error GoTo errLabel
  fColLetter = Split(Columns(lngCol).Address(, False), ":")(1)
  Exit Function
errLabel:
  fColLetter = "%ERR%"
End Function

파스칼 (Delphi)의 간단한 함수입니다.

function GetColLetterFromNum(Sheet : Variant; Col : Integer) : String;
begin
  Result := Sheet.Columns[Col].Address;  // from Col=100 --> '$CV:$CV'
  Result := Copy(Result, 2, Pos(':', Result) - 2);
end;

This formula will give the column based on a range (i.e., A1), where range is a single cell. If a multi-cell range is given it will return the top-left cell. Note, both cell references must be the same:

MID(CELL("address",A1),2,SEARCH("$",CELL("address",A1),2)-2)

How it works:

CELL("property","range") returns a specific value of the range depending on the property used. In this case the cell address. The address property returns a value $[col]$[row], i.e. A1 -> $A$1. The MID function parses out the column value between the $ symbols.


Easy way to get the column name

Sub column()

cell=cells(1,1)
column = Replace(cell.Address(False, False), cell.Row, "")
msgbox column

End Sub

I hope it helps =)


Sub GiveAddress()
    Dim Chara As String
    Chara = ""
    Dim Num As Integer
    Dim ColNum As Long
    ColNum = InputBox("Input the column number")

    Do
        If ColNum < 27 Then
            Chara = Chr(ColNum + 64) & Chara
            Exit Do
        Else
            Num = ColNum / 26
            If (Num * 26) > ColNum Then Num = Num - 1
            If (Num * 26) = ColNum Then Num = ((ColNum - 1) / 26) - 1
            Chara = Chr((ColNum - (26 * Num)) + 64) & Chara
            ColNum = Num
        End If
    Loop

    MsgBox "Address is '" & Chara & "'."
End Sub

So I'm late to the party here, but I want to contribute another answer that no one else has addressed yet that doesn't involve arrays. You can do it with simple string manipulation.

Function ColLetter(Col_Index As Long) As String

    Dim ColumnLetter As String

    'Prevent errors; if you get back a number when expecting a letter, 
    '    you know you did something wrong.
    If Col_Index <= 0 Or Col_Index >= 16384 Then
        ColLetter = 0
        Exit Function
    End If

    ColumnLetter = ThisWorkbook.Sheets(1).Cells(1, Col_Index).Address     'Address in $A$1 format
    ColumnLetter = Mid(ColumnLetter, 2, InStr(2, ColumnLetter, "$") - 2)  'Extracts just the letter

    ColLetter = ColumnLetter
End Sub

After you have the input in the format $A$1, use the Mid function, start at position 2 to account for the first $, then you find where the second $ appears in the string using InStr, and then subtract 2 off to account for that starting position.

This gives you the benefit of being adaptable for the whole range of possible columns. Therefore, ColLetter(1) gives back "A", and ColLetter(16384) gives back "XFD", which is the last possible column for my Excel version.


Column letter from column number can be extracted using formula by following steps
1. Calculate the column address using ADDRESS formula
2. Extract the column letter using MID and FIND function

Example:
1. ADDRESS(1000,1000,1)
results $ALL$1000
2. =MID(F15,2,FIND("$",F15,2)-2)
results ALL asuming F15 contains result of step 1

In one go we can write
MID(ADDRESS(1000,1000,1),2,FIND("$",ADDRESS(1000,1000,1),2)-2)


this is only for REFEDIT ... generaly use uphere code shortly version... easy to be read and understood / it use poz of $

Private Sub RefEdit1_Change()

    Me.Label1.Caption = NOtoLETTER(RefEdit1.Value) ' you may assign to a variable  var=....'

End Sub

Function NOtoLETTER(REFedit)

    Dim First As Long, Second As Long

    First = InStr(REFedit, "$")                 'first poz of $
    Second = InStr(First + 1, REFedit, "$")     'second poz of $

    NOtoLETTER = Mid(REFedit, First + 1, Second - First - 1)   'extract COLUMN LETTER

End Function

Cap A is 65 so:

MsgBox Chr(ActiveCell.Column + 64)

Found in: http://www.vbaexpress.com/forum/showthread.php?6103-Solved-get-column-letter


ASCII 숫자로 변환하고 Chr ()을 사용하여 문자로 다시 변환하는 것은 어떻습니까?

col_letter = Chr (선택 열 + 96)


다른 방법이 있습니다.

{

      Sub find_test2()

            alpha_col = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,W,Z" 
            MsgBox Split(alpha_col, ",")(ActiveCell.Column - 1) 

      End Sub

}

참고 URL : https://stackoverflow.com/questions/12796973/function-to-convert-column-number-to-letter

반응형