我正在创建一个使用 VBA 将位字符串转换为数字的 Excel 宏。它们不是二进制数,每个“1”代表它自己的数字。
例如:1100000000000000000010001
从左至右,第一位代表“1”,第二位代表“2”,第三位代表“0”,以此类推。每个字符串中的总位数为 25。
我希望 VBA 对其进行转换并显示如下结果:1、2、21、25。
我尝试使用 Text to Columns 但没有成功。
尝试这样的事情:
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
考虑:
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
这必须是VBA吗?给出这样的数据设置:
单元格 B4 中并复制到 B33 中的公式为:
=IF(ROWS(B$3:B3)>LEN($B$1)-LEN(SUBSTITUTE($B$1,"1","")),"",FIND("@",SUBSTITUTE($B$1,"1","@",ROWS(B$3:B3))))
公式单元格的格式设置为常规,位字符串单元格 (B1) 的格式设置为文本。
试试这个:
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
另一个非 VBA 解决方案,基于 OP 的初始方法,其布局旨在促进多次“转换”(即复制公式以适应):