如何使用单元格(x,y)值的变量填充excel中的表

时间:2013-05-23 15:13:35

标签: excel vba

过去几周我一直在不停地搜索堆栈,因为我学习了excel vb,但最后我很难过。

我需要使用x位置的变量和y位置的变量激活单元格。

xval是一个整数 yval是一个字符串

我正在尝试使用匹配功能,但没有运气。

这是我尝试过的。

Sheets("Attributes").Select      'this is the sheet with the raw data
Range("C2").Activate
Dim xval As String                'this is the row I'm looking for
Dim yval As Integer               'this is the colum I'm looking for
Dim value As String               'when I find the exact right cell on the next sheet this is the value that needs to go in it.

' start loop here

xval = ActiveCell.Offset(0, -2)   'populate variables
yval = ActiveCell
value = ActiveCell.Offset(0, 2)
Sheets("output").Select              'switch to output sheet
Range("A1").Activate

Cells(WorksheetFunction.Match(xval, "A:A", 0), WorksheetFunction.Match(yval, "A1:A500", 0)).Activate    'this line doesn't work


ActiveCell = value

'end loop when data runs out using is empty function

1 个答案:

答案 0 :(得分:0)

Sub Tester()

    Dim xval As String
    Dim yval As Integer
    Dim v As String
    Dim shtOut As Worksheet
    Dim f As Range

    Set shtOut = ThisWorkbook.Sheets("output")

    With ThisWorkbook.Sheets("Attributes").Range("C2")
        xval = .Offset(0, -2).value
        yval = .value
        v = .Offset(0, 2).value
    End With

    On Error Resume Next
    Set f = shtOut.Cells(WorksheetFunction.Match(xval, shtOut.Range("A:A"), 0), _
                      WorksheetFunction.Match(yval, shtOut.Range("A1:A500"), 0))
    On Error GoTo 0

    If Not f Is Nothing Then f.value = v

    'flag if not found
    ThisWorkbook.Sheets("Attributes").Range("C2").Font.Color = _
                               IIf(f Is Nothing, vbRed, vbGreen)


End Sub