【发布时间】:2015-06-30 03:56:11
【问题描述】:
我正在尝试创建一个生成秘密编码消息的函数。它包含三件事:一个字符串,例如“testingtestingonetwothree”,以及所需的字符数,例如 5,以及所需的单词数,例如 5。它从第一个字符开始生成消息,并通过字符串提取每五个字符,将这些字符放入一个代码字中,然后从第二个字符开始,通过字符串每隔五个字符提取一次,将它们放入第二个代码字中,依此类推。它只输出一个字符串,代码字用空格分隔。所以对于这个例子,它会产生:“tntnt egieh stntr tegwe isooe”。
我擅长编码,但对 VBA 很陌生。我已经做了我认为是有效的函数,但是当它在电子表格中使用时,我得到一个#VALUE!错误:“公式中使用的值是错误的数据类型”。这是我制作的用户定义函数:
Function encode(strng, numchars, numwords)
Dim word As Integer
Dim step As Integer
Dim temp As String
Dim output As String
For word = 1 To numchars
step = word
temp = ""
Do While step <= Len(strng)
temp = temp & Mid(strng, 1, step)
step = step + numchars
Loop
If word = 1 Then output = temp Else output = output & " " & temp
Next word
encode = output
End Function
当它在电子表格中使用时,我只是调用它,如
=encode(A16,A7,A10)
其中 A16 包含 testingtestingonetwothree,A7 包含 5,A10 包含 5。
我的功能看起来还好吗?你们有什么可以看到的可能导致价值错误的东西吗?任何帮助将不胜感激,非常感谢阅读。
编辑:现在输出一个值,但值错误。当它应该输出:“tntnt egieh stntr tegwe isooe”时,它输出:“ttestintestingtesttestingtestingontestingtestingonetwot tetestingtestingtestitestingtestingonetestingtestingonetwoth”。你们有什么可以看出我的函数做错了吗?
EDIT2:修复 Mid 功能后, temp = temp & Mid(strng, step, 1) 根据 vacip 的回答,该函数现在会产生正确的答案。
【问题讨论】:
-
它在这里工作....我只是复制和粘贴,没有任何更改....(它必须在一个单独的模块中,而不是在工作表模块中)
-
只是好奇:当你说它有效时,你的意思是它给了你想要的输出,或者你只是说它不会产生错误消息?
-
不会产生错误
-
值错误现在消失了。但是,在修复 Mid 函数后,它现在会生成“tienete ensgth sgtowr ttinoe”,而不是它应该输出的“tntnt egieh stntr tegwe isooe”。
-
嗯,我无法重现这个新错误。尝试在代码中添加断点,然后逐步检查,看看是否能找出问题所在。