gpt4 book ai didi

vba - vba 的单个子/函数中可以使用多少个变量?

转载 作者:行者123 更新时间:2023-12-02 23:38:58 24 4
gpt4 key购买 nike

我已经构建了一个简单的函数,但它需要大约 11-12 个具有相同整数类型的变量。每次我尝试使用超过 10 个变量时,第一个变量经常出错,而其他变量却计算正确。如果我将变量数量减少到 10 个,它们都是正确的。这是否意味着vba一次只能存储10个相同类型的变量?或者这是我的电脑的限制:))

这是我的代码,btb 返回错误的值,而其他值是正确的,但是如果我删除变量“a”以及与其相关的所有代码,则 btb 返回正确的值

Sub regionCount()
Dim btb, dbb, hn, ntb, dnb, tnbBS, tnbNS, hcm1, hcm2, hcm3, a As Integer

btb = dbb = hn = dnb = tnbBS = tnbNS = hcm1 = hcm2 = hcm3 = a = 0

For Each mycell In Worksheets(1).Range("E2:E382")
If mycell.Value = "Khu vuc Bac Trung Bo" Then
btb = btb + 1
ElseIf mycell.Value = "Khu vuc Dong Bac Bo" Then
dbb = dbb + 1
ElseIf mycell.Value = "Khu vuc Ha Noi" Then
hn = hn + 1
ElseIf mycell.Value = "Khu vuc Nam Trung Bo" Then
ntb = ntb + 1
ElseIf mycell.Value = "Khu vuc Dong Nam Bo" Then
dnb = dnb + 1
ElseIf mycell.Value = "Khu vuc Tay Nam Bo - Bac song hau" Then
tnbBS = tnbBS + 1
ElseIf mycell.Value = "Khu vuc Tay Nam Bo - Nam song hau" Then
tnbNS = tnbNS + 1
ElseIf mycell.Value = "Khu vuc TPHCM_1" Then
hcm1 = hcm1 + 1
ElseIf mycell.Value = "Khu vuc TPHCM_2" Then
hcm2 = hcm2 + 1
ElseIf mycell.Value = "Khu vuc TPHCM_3" Then
hcm3 = hcm3 + 1
ElseIf mycell.Value = "-- None --" Then
a = a + 1
End If
Next mycell

Range("C5").Value = btb
Range("d5").Value = dbb
Range("e5").Value = hn
Range("f5").Value = ntb
Range("g5").Value = dnb
Range("h5").Value = tnbBS
Range("i5").Value = tnbNS
Range("j5").Value = hcm1
Range("k5").Value = hcm2
Range("l5").Value = hcm3
Range("m5").Value = a

结束子

最佳答案

你的陈述

btb = dbb = hn = dnb = tnbBS = tnbNS = hcm1 = hcm2 = hcm3 = a = 0

应该是

btb = 0
dbb = 0
hn = 0
dnb = 0
tnbBS = 0
tnbNS = 0
hcm1 = 0
hcm2 = 0
hcm3 = 0
a = 0
<小时/>

考虑该声明

a = b = c

这被解释为

a = (b = c)

其中(b = c)是逻辑表达式。因此,如果 bc 的值相同(如果变量全部保留为 0 的默认初始化,则结果会如此)那么a将被设置为True(即-1)

您的语句布局方式会将最左边的值设置为 -1(如果行中有奇数个变量)或 0(如果行中有偶数个变量)。

<小时/>

还需要注意的是

Dim btb, dbb, hn, ntb, dnb, tnbBS, tnbNS, hcm1, hcm2, hcm3, a As Integer

相当于

Dim btb As Variant, dbb As Variant, hn As Variant, ntb As Variant, dnb As Variant, _
tnbBS As Variant, tnbNS As Variant, hcm1 As Variant, hcm2 As Variant, _
hcm3 As Variant, a As Integer

这不一样

Dim btb As Integer, dbb As Integer, hn As Integer, ntb As Integer, dnb As Integer, _
tnbBS As Integer, tnbNS As Integer, hcm1 As Integer, hcm2 As Integer, _
hcm3 As Integer, a As Integer

关于vba - vba 的单个子/函数中可以使用多少个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48162623/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com