在 VBA 中连接字符串

发布于 2024-12-09 12:14:07 字数 180 浏览 0 评论 0原文

我正在维护一个使用 VBA 用 Microsoft Access 编写的应用程序。

我浏览了一下我的代码,刚刚注意到我下意识地使用加号 (+) 而不是与符号将字符串连接在一起。我已经有几年没有用 VB6 编写代码了。这会导致任何问题吗?

一切看起来都很好,只需要几分钟就能修复,我只是好奇我在技术上是否做错了什么。

I'm maintaining an application written in Microsoft Access with VBA.

I'm glancing over my code and have just noticed I have subconsciously been concatenating strings together with the plus (+) symbol instead of the ampersand. It's been a few years since I've coded in VB6. Could this cause any issues?

Everything seems fine and it will only take a few minutes to fix, I'm just curious as to whether I'm technically doing anything wrong.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

递刀给你 2024-12-16 12:14:07

& 符号明确是一个字符串操作,而加号是重载的:

Dim num1 As Integer
num1 = RandomNumberBetween(1, 9)

Dim num2 As Integer
num2 = RandomNumberBetween(1, 9)

Dim randomAge As String 'trying to get a random age between 11 and 99

' works
randomDate = "Your age is " & num1 & num2 

'broken
randomDate = "Your age is " + num1 + num2 

当与数字一起使用时,加号将相加。

The ampersand is explicitly a string operation, while the plus is overloaded:

Dim num1 As Integer
num1 = RandomNumberBetween(1, 9)

Dim num2 As Integer
num2 = RandomNumberBetween(1, 9)

Dim randomAge As String 'trying to get a random age between 11 and 99

' works
randomDate = "Your age is " & num1 & num2 

'broken
randomDate = "Your age is " + num1 + num2 

When used with numbers the plus sign will add.

つ可否回来 2024-12-16 12:14:07

来自 VBA 立即窗口的一些示例(第三个和第四个之间的差异特别令人烦恼):

Print "5" & 6
56

Print 5 & 6
56

Print "5" + 6
 11 

Print "5" + "6"
56 

Print "Five" & 6
Five6

Print "Five" + 6 'Type mismatch

Print "5" & Null
5

Print "5" + Null
Null

Some examples, from the VBA immediate window (the difference between the third and fourth is particularly vexing):

Print "5" & 6
56

Print 5 & 6
56

Print "5" + 6
 11 

Print "5" + "6"
56 

Print "Five" & 6
Five6

Print "Five" + 6 'Type mismatch

Print "5" & Null
5

Print "5" + Null
Null
白况 2024-12-16 12:14:07

这可能会导致问题。

如果您使用加号或与号来连接字符串值,则结果是相同的

如果您使用加号将字符串与非字符串值连接,它将抛出错误

如果您使用与号vba将尝试“字符串化”之前的值连接。

因此 string_value + int_value + date_value 将出错并且 string_value & int_value & date_value 工作正常

This can cause issues.

If you use the plus or ampersand to concatenate string values the results are identical

If you use a plus to concatenate a string with a non string value it will throw an error

If you use an ampersand sign vba will try to 'stringify' the values before concatenating.

So string_value + int_value + date_value will error and string_value & int_value & date_value works fine

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文