当我不知道上限值时如何在excel vba中使用'ReDim Preserve'

时间:2019-01-17 10:49:46

标签: excel vba

我需要使用在处理.txt文件期间生成的变量值填充数组。但是上限取决于输入线。如何使以下功能正常工作?

Dim myArr As Variant
ReDim Preserve myArr(1)  ' this line does not work without a value

Do While (some condition)
    myArr=Trim(variable_name)
Loop

3 个答案:

答案 0 :(得分:2)

在循环中检查条件,并增加一个计数器,然后在1行中重新设置数组的格式。将有2个循环,但这仍然会更快。这是一种方法(未经测试

Dim myArr As Variant
Dim counter As Long

Do While (some condition)
    counter = counter + 1
Loop

ReDim myArr(counter) '<~~ No need of Preserve

counter = 0

Do While (some condition)
    myArr(counter) = Trim(variable_name)
    counter = counter + 1
Loop

答案 1 :(得分:1)

下面的一些代码片段应该可以帮助您理解:

  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-eslint": "^10.0.1",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.7.0",
    "eslint": "^5.12.0",
    "eslint-config-prettier": "^3.4.0",
    "eslint-config-standard": "^12.0.0",
    "eslint-plugin-import": "^2.14.0",
    "eslint-plugin-node": "^8.0.1",
    "eslint-plugin-promise": "^4.0.1",
    "eslint-plugin-standard": "^4.0.0",
    "husky": "^1.3.1",
    "jest": "^23.6.0",
    "lint-staged": "^8.1.0",
    "nodemon": "^1.18.9",
    "prettier": "^1.15.3",
    "rimraf": "^2.6.3"
  },

答案 2 :(得分:0)

通过使用计数器:

Dim myArr As Variant
Dim counter as Integer

Do While (some condition)
    ReDim Preserve myArr(counter)
    myArr(counter)=Trim(variable_name)
Loop

使它比伪代码更进一步

Dim myArr as Variant
Dim counter as Integer
Dim x as Integer
x = 2

Do While x < 10
    ReDim Preserve myArr(counter)
    myArr(counter) = x
    debug.print Ubound(myArr)
    debug.print myArr(counter)
    x = x * 2 
Loop