更改颜色的特定范围

时间:2015-08-22 21:17:58

标签: excel vba excel-vba

我有一张Excel表格,如下所示:

enter image description here

我想根据C和D的值更改E列中字符的颜色。

输出应如下所示:

enter image description here

public class DeviceDemo {
    public static void main(String[] args) throws Exception {
        // Initialize
        // On unix this will result in the equivalent of $HOME/.powercontrol/storage/device.xml
        Path file = Paths.get(System.getProperty("user.home"), ".powercontrol", "storage", "device.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Device.class);

        // Read
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        InputStream inputStream = new FileInputStream(file.toFile);
        Device device = (Device) unmarshaller.unmarshal(inputStream);
        inputStream.close();

        // Update
        device.setName("Updated name");
        device.setHost("Updated host");
        device.setPort(2302);

        // Write
        Marshaller marshaller = jaxbContext.createMarshaller();
        OutputStream outputStream = new FileOutputStream(file.toFile);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(device, outputStream);
        outputStream.close();
    }
}

因此,列E的颜色应在1到3的位置发生变化。

1 个答案:

答案 0 :(得分:2)

您可以使用Characters功能更改单元格文本中某些字符的属性。 Characters()的第二个参数是长度,而不是结尾,所以你只需要做一些数学运算就可以从你的例子到你需要的地方。

例如:

Dim r As Range, intStart As Long, intEnd As Long

For Each r In Range("E1:E3")
    intStart = r.Offset(, -2)
    intEnd   = r.Offset(, -1)
    r.Characters(intStart, intEnd - intStart + 1).Font.Color = RGB(255, 0, 0)
Next