求一段vba代码

2026年09月09日 17:35
有1个网友回答
网友(1):

我用VBS做过,建议你用VBS吧:把下面的代码复制粘贴到记事本,保存为一个.VBS的文件,例如24.VBS,然后鼠标双击就可以执行它。

全部代码如下:

'24点计算程序,输入4个1~10之间的数字,组合计算值为24点的结果
dim num(4)
set re=New RegExp
re.Pattern="\s+"
re.Global=true
do while 1
  str=re.replace(trim(inputbox("用空格分开,每个数在1~10之间:","输入4个数"))," ")
  if str="" then exit do
  arr=split(str," ")
  if ubound(arr)=3 then
    for i=0 to 3
      num(i)=arr(i)+0
    next
    tim=now
    test=0
    do while 1
      '随机排序
      for i=3 to 1 step -1
        j=int(rnd*i)
        if j<>i then
          t=num(j)
          num(j)=num(i)
          num(i)=t
        end if
      next
      'msgbox join(num," ")
      '随机计算
      sum=num(0)
      str=num(0)
      t2=2'上一次的运算符号
      for i=1 to 3
        '随机计算方法:0+ 1- 2* 3/
        if (sum<>0 and num(i)<>0) then
          if (sum mod num(i)=0 or num(i) mod sum=0) then t=4 else t=3
        else
          t=3
        end if
        t=int(rnd*t)
        '如果上次为+-、本次为*/则给前面的加上括号
        if t2<2 and t>1 then str="(" & str & ")"
        t2=t
        select case t
          case 0:sum=sum+num(i):str=str & " + " & num(i)
          case 1:
            if sum>num(i) then 
              sum=sum-num(i)
              str=str & " - " & num(i)
            else
              sum=num(i)-sum
              if i>1 then str=num(i) & " - (" & str &")" else str=num(i) & " - " & str
            end if
          case 2:sum=sum*num(i):str=str & " * " & num(i)
          case 3:
            if sum>num(i) then
              sum=sum/num(i)
              str=str & " / " & num(i)
            else
              sum=num(i)/sum
              if i>1 then str=num(i) & " / (" & str &")" else str=num(i) & " / " & str
            end if
        end select
      next
      '判断结果
      if sum=24 then msgbox str,,"成功": exit do
      test=test+1
      if (now-tim)*24*3600>5 then msgbox "测试"& test &"次:" & join(num," "),,"失败":exit do
    loop
  end if
loop