简体   繁体   中英

How to write in a cell based on another cell

I'm trying to check if a cell in one sheet has a certain value, and if that's the case write a text string in another cell in another sheet.

Afterwards I would like to call the same sub in some range in the first sheet and apply it to the corresponding range in the other sheet. The ranges don't have them same location, only the same size.

Here is an example:
在此处输入图片说明

The first binary matrix is in the first sheet. (The location could as an example be in A1:B2).
The second matrix is made based on the first matrix (The location could as an example be in A1:B2).

This is my idea so far (notice, it isn't working yet)

Sub Convert(SomeCell, AnotherCell)
    If Worksheets("Sheet1").Range(SomeCell).Value > 0 Then
        Worksheets("Sheet2").Range(AnotherCell).Value = "String"
    End If
End Sub

EDIT

I'm searching for the corresponding VBA code for this IF statement formula

= IF(Sheet1!A1>0;"String";"")

Which then can be dragged in some range.

This might give you an idea:

Sub Convert(Source As Range, Target As Range, Replace As Variant)
    'Takes a binary matrix in source range and fills in target range
    'with value Replace taking the place of 1
    'assumes equal sized ranges
    
    Dim i As Long, j As Long
    For i = 1 To Source.Rows.Count
        For j = 1 To Source.Columns.Count
            If Source.Cells(i, j).Value = 1 Then Target.Cells(i, j).Value = Replace
        Next j
    Next i
End Sub

Called like:

Sub test()
    Convert Sheets(1).Range("A1:B2"), Sheets(2).Range("A1:B2"), "String"
End Sub

There are probably better ways to do it, but this will give you a way to represent a binary matrix in one sheet with a string matrix in another (if that is what you were trying to do). Note that unexpected results could occur if the source and target range overlap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM