如何用Excel VBA填充A、B列:A为起始1的整数,B=n^5-10n^4且<100000
Excel VBA 填充A、B列解决方案
原代码的问题
- 未初始化
columnA、columnB的初始值,且i、k变量未定义,直接读取单元格值会出错 - 循环条件逻辑错误:
Do Until columnB < 100000意味着直到columnB小于100000才停止循环,和需求完全相反 - 仅修改了变量值,没有将计算结果写入Excel单元格,导致表格无变化
正确的VBA代码(两种写法)
写法1:Do循环+条件判断退出
Sub FillABColumns() Dim n As Integer Dim currentRow As Integer Dim bResult As Double currentRow = 1 '从第一行开始填充 n = 1 'A列起始整数为1 Do '计算B列对应值 bResult = n ^ 5 - 10 * n ^ 4 '当结果不小于100000时,停止循环 If bResult >= 100000 Then Exit Do '将值写入单元格 Cells(currentRow, 1).Value = n Cells(currentRow, 2).Value = bResult '更新下一组数据的参数 n = n + 1 currentRow = currentRow + 1 Loop End Sub
写法2:Do While循环
Sub FillABColumns_Alternative() Dim n As Integer Dim currentRow As Integer Dim bResult As Double currentRow = 1 n = 1 '先计算第一个值,作为循环判断的初始条件 bResult = n ^ 5 - 10 * n ^ 4 '当B列值小于100000时,继续循环填充 Do While bResult < 100000 Cells(currentRow, 1).Value = n Cells(currentRow, 2).Value = bResult '更新参数,计算下一个值 n = n + 1 bResult = n ^ 5 - 10 * n ^ 4 currentRow = currentRow + 1 Loop End Sub
代码说明
n:A列的整数,从1开始递增currentRow:记录当前填充的行号,确保数据依次写入表格bResult:存储n^5 -10n^4的计算结果,用于判断是否继续循环- 两种写法都能实现需求:A列填充从1开始的整数,B列对应计算值,直到B列值≥100000时停止
内容的提问来源于stack exchange,提问作者Lisa02
相关产品推荐
相关产品推荐

