如何遍历字符串并检查每个字符的字节值?

时间:2020-03-05 18:58:03  来源:igfitidea点击:

代码我有:

cell_val = CStr(Nz(fld.value, ""))
        Dim iter As Long
        For iter = 0 To Len(cell_val) - 1 Step 1
         If Asc(Mid(cell_val, iter, 1)) > 127 Then
           addlog "Export contains ascii character > 127"
         End If
        Next iter

此代码无效。有人知道怎么做吗?我对VB或者VBA完全一无所知。

解决方案

回答

我相信问题是在VBA中,字符串索引从1开始而不是从0开始。请尝试以下操作:

For iter = 1 To Len(cell_val) 
    If Asc(Mid(cell_val, iter, 1)) > 127 Then
        addlog "Export contains ascii character > 127"
    End If
Next

回答

你调试了吗? ;)我们确定cell_val不为空吗?另外,由于它是默认设置,因此我们不需要For循环中的"步骤1"。我们还希望代码完成什么?它记录是否有大于127的ascii值?就是这样,没有分支取决于结果吗?

回答

试试AscW()

回答

VB / VBA字符串基于1而不是0,因此我们需要使用:

For iter = 1 To Len(cell_val)

由于这是默认设置,因此我也省略了"步骤1"。

回答

示例应进行修改,使其不具有外部依赖关系,现在它依赖于Nz和addLog。

无论如何,这里的问题似乎是我们从0循环到len()-1. 在VBA中,该值为1到n。

Dim cell_val As String
 cell_val = "?abcd???~!#%&/()"
 Dim iter As Long
 For iter = 1 To Len(cell_val)
    If Asc(Mid(cell_val, iter, 1)) > 127 Then
       'addlog "Export contains ascii character > 127"
       Debug.Print iter, "Export contains ascii character > 127"
    End If
 Next iter

回答

Did you debug it? ;) Are you sure the
  cell_val is not empty? Also you don't
  need the 'Step 1' in the For loop
  since it's default. Also what do you
  expect to acomplish with your code? It
  logs if any ascii values are above
  127? But that's it - there is no
  branching depending on the result?

我没有调试它,我也不知道如何使用vba或者它附带的任何工具。
是的,我确定cell_val不为空。
该代码具有代表性,在编写分支本身之前,我确保分支条件有效。

I believe your problem is that in VBA string indexes start at 1 and not at 0.

啊,我一定会错过与vba一起出现的确切事情,谢谢。

回答

使用VBA,VB6,我们只需声明一个字节数组并为其分配一个字符串值,它将为我们转换。然后,我们可以像常规数组一样遍历它。

例如

Dim b() as byte
Dim iter As Long
b = CStr(Nz(fld.value, ""))

For iter = 0 To UBound(b)
    if b(iter) > 127 then
        addlog "Export contains ascii character > 127"
    end if
next