如何清理此代码以使其更容易和更具适应性?

时间:2018-11-29 16:39:12

标签: excel vba

正在寻找有关如何清理此代码的建议,以使其更易于阅读,并且在我需要扩展行数的情况下更具有适应性。具体来说,是如何告诉代码选择哪个单元格,以及在每个单元格中定位哪些值。

qWordCount = WorksheetFunction.Sum(Worksheets("Words").Range("B:B"))

Cells(2, 5) = "Hyphens"
Cells(2, 6) = tHyphenCount
Cells(2, 7) = Round(qWordCount / tHyphenCount, 2)

Cells(3, 5) = "Brackets"
Cells(3, 6) = rBracketCount / 2
Cells(3, 7) = Round(qWordCount / (rBracketCount / 2), 2)

Cells(4, 5) = "Quotation Marks"
Cells(4, 6) = vQuotationMarkCount
Cells(4, 7) = Round(qWordCount / vQuotationMarkCount, 2)

Cells(5, 5) = "Full Stops"
Cells(5, 6) = zFullStopCount
Cells(5, 7) = Round(qWordCount / zFullStopCount, 2)

Cells(6, 5) = "Question Marks"
Cells(6, 6) = yQuestionMarkCount
Cells(6, 7) = Round(qWordCount / yQuestionMarkCount, 2)

Cells(7, 5) = "Colons"
Cells(7, 6) = xColonCount
Cells(7, 7) = Round(qWordCount / xColonCount, 2)

Cells(8, 5) = "Commas"
Cells(8, 6) = wCommaCount
Cells(8, 7) = Round(qWordCount / wCommaCount, 2)

Cells(9, 5) = "Semicolons"
Cells(9, 6) = uSemiColonCount
Cells(9, 7) = Round(qWordCount / uSemiColonCount, 2)

Cells(10, 5) = "Exclamation Marks"
Cells(10, 6) = sExclamationMarkCount
Cells(10, 7) = Round(qWordCount / sExclamationMarkCount, 2)

Cells(11, 5) = "Word Count"
Cells(11, 6) = qWordCount

2 个答案:

答案 0 :(得分:2)

我喜欢您的代码,但您也可以这样做

public sub embed(lRow as long,lCol as long,strFirst as string,strMacro as string,dNum as double, dDen as double)

    cells(lRow,lCol) = strFirst
    cells(lRow,lCol+1) = application.run(strMacro)
    cells(lRow,lCol+2) = Round(dNum / dDen, 2)

end sub

public sub main()

    embed 2,5,"Hyphens","tHyphenCount",qWordCount,tHyphenCount
    'Replace the remainder of the blocks of code with embed calls, aside from the last 2, which doesn't fit this model

end sub

答案 1 :(得分:0)

您可以为其创建通用过程。请注意,当f = mp3play.load('FULL ADDRESS/Sound.mp3'); play = lambda: f.play() 本身被二除时,代码处理的是括号的特殊情况。为了应用此除法,请为rBracketCount参数传递True。默认情况下为is_divide

False