如何为单元格分配值?

时间:2019-08-24 19:55:52

标签: excel vba

我正在尝试导入文本文件并在Excel中对其进行处理。

第一步是将数据分为两组:标头和内容。

我创建了两个工作表。然后导入文本数据。然后确定数据文件的高度,宽度和项目数。

问题来了,试图将标头数据复制到工作表之一。我没有任何价值。

我尝试将值分配为:

Worksheets("TIME").Range(Cells(j, k)).Value = Range(Cells(i, k)).Value

作为固定值:

Worksheets("TIME").Range(Cells(j, k)).Value = 1

我在循环上放置了一个计数器,它们工作正常。

On Error Resume Next
Worksheets.Add.Name = "RAW"
Worksheets.Add.Name = "TIME"
Sheets("RAW").Select

'Import and copy data to RAW sheet. It is working so I did not copy it.

Range("A1").End(xlToRight).Select
WidthFile = ActiveCell.Column
Range("A1").End(xlDown).Select
HeightFile = ActiveCell.Row
Range("A1").Select
NumberObs = Application.WorksheetFunction.CountIf(ActiveSheet.Range _
              (Cells(1, 1), Cells(HeightFile, 1)), Range("A1").Value)
Sample = Range("A1").Value
j = 1

For i = 2 To HeightFile
    If Range(Cells(i, 1)).Value = Sample Then
        For k = 1 To WidthFile
            Worksheets("TIME").Range(Cells(j, k)).Value = _
                               Range(Cells(i, k)).Value
        Next
        j = j + 1
    End If
Next

我希望将RAW工作表上与第一个单元格匹配的原始数据行与在“ TIME”工作表上复制的“ RAW”工作表上的第一个单元格匹配作为导入数据。我有一个空白工作表。

我在RAW工作表中获得的数据文件如下:
RAW DATA

TIME工作表上的预期结果应为:
TIME工作表预期结果示例
TIME DATA

1 个答案:

答案 0 :(得分:0)

建议在单个对象上执行多条语句时使用Objects并使用With statement:即使用此:

With Range("A1")
   WidthFile = .End(xlToRight).Column
   HeightFile= .End(xlDown).Row
End With

代替此:

Range("A1").End(xlToRight).Select
WidthFile = ActiveCell.Column
Range("A1").End(xlDown).Select
HeightFile = ActiveCell.Row

还请注意,Worksheet.Cells property (Excel)返回一个Range,因此请使用以下命令:

.Cells(j, k).Value

代替此:

.Range(Cells(j, k)).Value

我已经对您提供的代码进行了一些调整。试试这个:

Sub test()
Dim wsRaw As Worksheet
Dim wsTime As Worksheet
Dim lRows As Long, lCols As Long
Dim lNbrObs As Long, vSample As Variant
Dim j As Long, i As Long, k As Long

    Rem Add these lines after the worksheets had been added
    With ThisWorkbook
        Set wsRaw = .Worksheets("RAW")
        Set wsTime = .Worksheets("TIME")
    End With

    With wsRaw

        lRows = .Cells(1).End(xlDown).Row
        lCols = .Cells(1).End(xlToRight).Column
        vSample = .Cells(1).Value2
        lNbrObs = Application.WorksheetFunction _
            .CountIf(.Cells(1).Resize(lRows), vSample)

        For i = 2 To lRows
            If .Cells(i, 1).Value2 = vSample Then
                j = 1 + j
                For k = 1 To lCols
                    wsTime.Cells(j, k).Value2 = .Cells(i, k).Value2

    Next: End If: Next: End With

    End Sub