如何将位数转换为数字

时间:2013-09-06 18:32:33

标签: excel vba excel-vba

我正在使用VBA创建一个Excel宏来将位字符串转换为数字。它们不是二进制数,每个'1'代表它自己的数字。

例如:1100000000000000000010001

从左边开始,第一位表示“1”,第二位表示“2”,第三位表示“0”,依此类推。每个字符串中的总位数为25。

我希望VBA转换它并显示如下结果:1,2,21,25。

我尝试使用Text to Columns,但没有成功。

5 个答案:

答案 0 :(得分:1)

尝试这样的事情:

Sub Execute()
    Dim buff() As String
    Dim i As Integer, total As Double

    buff = Split(StrConv(<theString>, vbUnicode), Chr$(0))
    total = 0

    For i = 0 To UBound(buff)
        Debug.Print (buff(i))
        'total = total + buff(i) * ??
    Next i
End Sub

答案 1 :(得分:1)

考虑:

Public Function BitPicker(sIn As String) As String
    For i = 1 To Len(sIn)
        If Mid(sIn, i, 1) = 1 Then
            BitPicker = BitPicker & i & ","
        End If
    Next
        BitPicker = Mid(BitPicker, 1, Len(BitPicker) - 1)
End Function

答案 2 :(得分:0)

这必须是VBA吗?提供如下数据设置:

Convert from bit string

单元格B4中的公式并向下复制到B33:

=IF(ROWS(B$3:B3)>LEN($B$1)-LEN(SUBSTITUTE($B$1,"1","")),"",FIND("@",SUBSTITUTE($B$1,"1","@",ROWS(B$3:B3))))

公式单元格格式为General,而Bit String单元格(B1)格式为Text。

答案 3 :(得分:0)

试试这个:

  Function ConvertMyRange(Rng As Range) As String

  Dim MyString As String
  MyString = Rng.Text
  Dim OutPutString As String

     For i = 1 To Len(MyString)
        If Mid(MyString, i, 1) = "1" Then OutPutString = OutPutString & ", " & i
     Next i

     ' Get rid of first ", " that was added in the loop
     If Len(OutPutString) > 0 Then
        OutPutString = Mid(OutPutString, 2)
     End If

     ConvertMyRange = OutPutString

  End Function

对于您的输入,输出为1,2,21,25

答案 4 :(得分:0)

另一种非VBA解决方案,基于OP的初始方法,并采用旨在促进多次“转换”的布局(即复制公式以适应):

enter image description here