VBA枚举以避免复制/粘贴

时间:2015-02-22 16:12:47

标签: vba word-vba

我不确定如何命名,如果您可以更具描述性,请随时更新。

这就是我要做的事情。我有一个非常重复的代码,它具有一个非常可预测的变量模式,可以使每个实例都不同。

'Make sure decimal character is ","

Call SetLocalSetting(LOCALE_SDECIMAL, ",")


'_01 -------------------------------------------------------------

qty_01 = Val(ActiveDocument.Tables(5).Cell(2, 2).Range.Text)

'qty_01 is now ready to be used for calculations. Next is price_01.

price_01 = ActiveDocument.Tables(5).Cell(2, 3).Range.Text
price_01 = Replace(price_01, ",", ".")
price_01 = Format(Val(price_01), "##,##0.00")

'price_01 is now ready to be used for calculations. Next are price_01_cro and price_01_eng.

price_01_cro = price_01
price_01_eng = price_01
price_01_eng = Replace(price_01_eng, ",", "decSym")
price_01_eng = Replace(price_01_eng, ".", "thoSym")
price_01_eng = Replace(price_01_eng, "decSym", ".")
price_01_eng = Replace(price_01_eng, "thoSym", ",")

'price_01_cro and price_01_eng are now ready to be used for presentation.


'_02 -------------------------------------------------------------

qty_02 = Val(ActiveDocument.Tables(5).Cell(3, 2).Range.Text)

'qty_02 is now ready to be used for calculations. Next is price_02.

price_02 = ActiveDocument.Tables(5).Cell(3, 3).Range.Text
price_02 = Replace(price_02, ",", ".")
price_02 = Format(Val(price_02), "##,##0.00")

'price_02 is now ready to be used for calculations. Next are price_02_cro and price_02_eng.

price_02_cro = price_02
price_02_eng = price_02
price_02_eng = Replace(price_02_eng, ",", "decSym")
price_02_eng = Replace(price_02_eng, ".", "thoSym")
price_02_eng = Replace(price_02_eng, "decSym", ".")
price_02_eng = Replace(price_02_eng, "thoSym", ",")

'price_02_cro and price_02_eng are now ready to be used for presentation.

它持续11次。有什么方法更方便,而不是一遍又一遍地复制相同的东西,并改变数字?

顺便说一句,这是我继续努力建立发票生成器。这就是为什么我必须使用一些黑客来处理Word处理小数字时的奇怪之处。

谢谢!

1 个答案:

答案 0 :(得分:2)

如果不更好地了解您正在操作的数据,我无法全面测试这一点,但是如果将变量设置为数组并进行迭代呢?它看起来像这样:

Call SetLocalSetting(LOCALE_SDECIMAL, ",")
Dim qty(0 To 10) As Variant
Dim price(0 To 10) As Variant
Dim price_cro(0 To 10) As Variant
Dim price_eng(0 To 10) As Variant

For inum = 0 To 10

qty(inum) = Val(ActiveDocument.Tables(5).Cell(inum + 1, 2).Range.Text)
price(inum) = ActiveDocument.Tables(5).Cell(inum + 1, 3).Range.Text
price(inum) = Replace(price(inum), ",", ".")
price(inum) = Format(Val(price(inum)), "##,##0.00")
price_cro(inum) = price(inum)
price_eng(inum) = price(inum)
price_eng(inum) = Replace(price_eng(inum), ",", "decSym")
price_eng(inum) = Replace(price_eng(inum), ".", "thoSym")
price_eng(inum) = Replace(price_eng(inum), "decSym", ".")
price_eng(inum) = Replace(price_eng(inum), "thoSym", ",")

Next