使用数字VBA填充部分填充的数组的行

时间:2015-04-10 15:53:48

标签: arrays excel vba

我试图解决的问题在理论上非常简单,但我真的很难投入到VBA代码中。 基本上,我的问题是:用户在开头输入包含数字的文件,这将被读作n,并且读入数组的矩阵,大小为nxn,已经部分填充,我需要填充每一行数字1到n,每个数字只出现一次。我需要为给定数组中的每一行执行此操作。

所以,我需要查看每一行,查看它包含的数字,并用不包含的数字填空。

以下是我的大部分代码:

Sub Problem()

    'Define the variables
    Dim n As Integer
    Dim i As Integer
    Dim j As Integer
    Dim inputFileName As String

    'Ask the user for the input file name
    inputFileName = InputBox("Enter Problem Filename (include .txt extension)")
    inputFileName = ActiveWorkbook.Path & "\" & inputFileName
    Open inputFileName For Input As #1

    'Read in the variable n at the top of the file
    Input #1, n

    'Construct the (n x n) matrix that will hold the problem and read in the problem from the input file
    ReDim Matrix(1 To n, 1 To n) As Integer
    For i = 1 To n
        For j = 1 To n
            Input #1, Matrix(i, j)
        Next j
    Next i

    Close #1

    '**************************************************************
    'Make a random starting solution
    ReDim sol(1 To n, 1 To n) As Integer
    initialSolution sol, Matrix, n

End Sub

我使用名为initialSolution的小型子程序获得初始解决方案,但这是我坚持的部分。这是Sub的基本概要,我还没有填写:

Sub initialSolution(sol() As Integer, Matrix() As Integer, n As Integer)

End Sub

1 个答案:

答案 0 :(得分:0)

不确定这是否是您正在寻找的内容:

Dim Counter: Counter = 1
Dim f, i
n = 15 'n=InputBox return
For f = 1 To n
    For i = 1 To n
        Cells(f, i).Value = Counter
        Counter = Counter + 1
    Next
Next